React-native-Agenda how to add a new item to the Agenda - javascript

I'm trying to add values ​​through the Modal inputs and I'm able to save and print these values, but I need to add them to the Agenda.
The Agenda asks for an object and even though I created an object, the Agenda says that it is either an array or a string and does not accept the type in the prop items.
What would be the function that will print correctly in the Agenda?
My code:
import React, { useEffect, useState } from 'react'
import { StyleSheet, View, Text, TouchableOpacity, Modal, TextInput, Alert } from 'react-native'
import { LocaleConfig, Agenda } from 'react-native-calendars'
import DateTimePicker from 'react-native-modal-datetime-picker';
import { Feather } from '#expo/vector-icons';
import { Ionicons } from '#expo/vector-icons';
import { Fontisto } from '#expo/vector-icons';
LocaleConfig.locales['tr'] = {
monthNames: ["Janeiro", "Fevereiro", "Março", "Abril", "Maio" ,"Junho" ,"Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"],
monthNamesShort: ["Jan", "Fev", "Mar", "Abr", "Mai", "Jun", "Jul", "Ago", "Set", "Out", "Nov", "Dez"],
today: "Hoje",
dayNames: ["Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado", "Domingo"],
dayNamesShort: ["Seg", "Ter", "Qua", "Qui", "Sex", "Sáb", "Dom"]
}
LocaleConfig.defaultLocale = "tr"
const Calendario = () => {
const [modalVisible, setModalVisible] = useState(false);
// informações que serão adicionadas ao calendário
const [events, setEvents] = useState(null);
const [dateSelected, setDateSelected] = useState('');
const [description, setDescription] = useState({});
const [refreshCalender, setRefreshCalender] = useState(false);
const item = {
data: "2022-07-26",
title: "teste",
description: "teste"
}
const renderItem = (item) => {
return(
<View style={styles.itemContainer}>
<Text>{item.title}</Text>
<Text>{item.description}</Text>
</View>
)
}
const [isDatePickerVisible, setDatePickerVisibility] = useState(false);
const showDatePicker = () => {
setDatePickerVisibility(true);
};
const hideDatePicker = () => {
setDatePickerVisibility(false);
};
const handleConfirm = (date) => {
console.log("A date has been picked: ", date);
setDateSelected(date);
hideDatePicker();
};
return (
<>
<Agenda
items={item}
renderEmptyDate={() => {
return <View />;
}}
renderEmptyData={() => {
return <View />;
}}
selected={new Date()}
minDate={null}
renderItem={renderItem}
markingType="custom"
refreshing={refreshCalender}
/>
<View>
<Modal
animationType="slide"
transparent={true}
visible={modalVisible}
onRequestClose={() => {
Alert.alert('Modal has been closed.');
setModalVisible(!modalVisible);
}}>
<View style={styles.centeredView}>
<View style={styles.modalView}>
<Text style={styles.modalText}>Adicione um horário</Text>
<TextInput
placeholder='Título'
onChangeText={(text) => setEvents(text)}
style={styles.input}
/>
<TextInput
placeholder='Descrição'
onChangeText={(text) => setDescription(text)}
style={styles.input}
/>
<TouchableOpacity
style={styles.btnDatePicker}
onPress={showDatePicker}
>
<Text>Selecionar data</Text>
<Fontisto name="date" size={20} color="#fff" style={{ margin: 10 }} />
</TouchableOpacity>
<DateTimePicker
mode='date'
minimumDate={null}
isVisible={isDatePickerVisible}
onConfirm={handleConfirm}
onCancel={hideDatePicker}
/>
<TouchableOpacity
style={[styles.button2, styles.buttonClose2]}
onPress={() => {
console.log(events)
console.log(description)
console.log(dateSelected)
console.log(typeof(dateSelected))
setModalVisible(false)
}}>
<Text style={styles.textStyle}>
<Ionicons name="checkmark-sharp" size={24} color="black" />
</Text>
</TouchableOpacity>
<TouchableOpacity
style={[styles.button, styles.buttonClose]}
onPress={() => setModalVisible(!modalVisible)}>
<Text style={styles.textStyle}>
<Feather name="x-circle" size={24} color="black" />
</Text>
</TouchableOpacity>
</View>
</View>
</Modal>
<TouchableOpacity style={styles.btn}
onPress={() => setModalVisible(true)}
>
<Ionicons name={'add-outline'} size={30} color={'black'}/>
</TouchableOpacity>
</View>
</>
)
}
export default Calendario
const styles = StyleSheet.create({
itemContainer: {
backgroundColor: "#fff",
margin: 5,
borderRadius: 15,
justifyContent: "center",
alignItems: "center",
flex: 1,
},
centeredView: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
marginTop: 22,
},
modalView: {
margin: 20,
backgroundColor: 'white',
borderRadius: 20,
width: "90%",
height: "60%",
alignItems: 'center',
shadowColor: '#000',
shadowOffset: {
width: 0,
height: 2,
},
shadowOpacity: 0.25,
shadowRadius: 4,
elevation: 5,
},
button: {
borderRadius: 20,
padding: 10,
elevation: 2,
position: "absolute",
right: 0,
bottom: 0,
margin: 15,
},
button2: {
borderRadius: 20,
padding: 10,
elevation: 2,
position: "absolute",
left: 0,
bottom: 0,
margin: 15,
},
buttonOpen: {
backgroundColor: '#F194FF',
},
buttonClose: {
backgroundColor: 'red',
},
buttonClose2: {
backgroundColor: '#9beb34',
},
textStyle: {
color: 'white',
fontWeight: 'bold',
textAlign: 'center',
},
modalText: {
marginBottom: 15,
textAlign: 'center',
fontWeight: "bold",
fontSize: 24,
margin: 10
},
btn: {
position: "absolute",
right: 0,
bottom: 0,
backgroundColor: "#0782F9",
padding: 10,
borderRadius: 30,
alignItems: "center",
margin: 15
},
input: {
width: "90%",
backgroundColor: "white",
paddingHorizontal: 15,
paddingVertical: 10,
borderRadius: 10,
marginTop: 5,
borderBottomWidth: 2,
borderBottomColor: "#313131"
},
dateComponent: {
width: "60%",
marginTop: 20,
marginBottom: 5,
},
btnDatePicker: {
padding: 15,
marginHorizontal: 10,
alignItems: "center",
backgroundColor: "#0782F9",
marginTop: 20,
width: "40%",
borderRadius: 15,
},
});

As per library mention you item is object and this object contains a key as a date and this key contain array so you item data look like
const item = {
"2022-07-26":[{name:"teste",description: "teste"}]
}
return (
<>
<Agenda
items={item}
renderEmptyDate={() => {
return <View />;
}}
renderEmptyData={() => {
return <View />;
}}
selected={new Date()}
minDate={null}
renderItem={renderItem}
markingType="custom"
refreshing={refreshCalender}
/>
</>
)
}
export default Calendario

Related

TypeError: undefined is not an object (evaluating '_app.default.initializeApp')

i got this problem when i try to save all date in firebase realTime Database pressing submit.
ERROR TypeError: undefined is not an object (evaluating '_app.default.initializeApp')
import firebase from 'firebase';
import React, { useState } from 'react';
import { View, Text, Modal, TouchableOpacity, FlatList, StyleSheet, DatePickerIOS, Image } from 'react-native';
import { Picker } from '#react-native-picker/picker';
const App = () => {
const [chosenDate, setChosenDate] = useState(new Date());
const [selectedValue, setSelectedValue] = useState('Alege Specializarea');
const [selectedDoctor, setSelectedDoctor] = useState('');
const [modalVisible, setModalVisible] = useState(false);
const [showPicker, setShowPicker] = useState(false);
const [showButtons, setShowButtons] = useState(false);
const options = ['Alege Specializarea', 'Cardiologie', 'Dermatologie', 'Oftalmologie', 'Analize Medicale'];
const optionMapping = {
'Alege Specializarea': [],
'Cardiologie': ['Dr. Alex', 'Dr. Balut'],
'Dermatologie': ['Dr. Chloe', 'Dr. David'],
'Oftalmologie': ['Dr. Emily', 'Dr. Frank'],
'Analize Medicale': ['Dr. Grace', 'Dr. Henry'],
};
const firebaseConfig = {
apiKey: "AIzaSyBhyYCXEaUlXqr83GtcbAfV2fiFooGzm2k",
authDomain: "first-app-7901e.firebaseapp.com",
databaseURL: "https://first-app-7901e-default-rtdb.europe-west1.firebasedatabase.app",
projectId: "first-app-7901e",
storageBucket: "first-app-7901e.appspot.com",
messagingSenderId: "876718439254",
appId: "1:876718439254:web:afe7784b89f066210334f7",
};
firebase.initializeApp(firebaseConfig);
const writeAppointmentData = (appointment) => {
firebase
.database()
.ref('appointments/' + appointment.id)
.set(appointment);
};
// Read data from the database
const readAppointmentData = (appointmentId) => {
return firebase
.database()
.ref('appointments/' + appointmentId)
.once('value')
.then((snapshot) => {
return snapshot.val();
});
};
const handleSubmit = () => {
const appointment = {
date: chosenDate,
specialization: selectedValue,
doctor: selectedDoctor,
};
writeAppointmentData(appointment);
setModalVisible(true);
};
const handleRead = () => {
readAppointmentData(appointmentId).then((appointment) => {
setAppointment(appointment);
});
};
return (
<>
<View style={styles.container}>
<Image source={require('./book.png')} style={styles.image} />
</View>
<View style={styles.container}>
<DatePickerIOS
date={chosenDate}
onDateChange={setChosenDate}
minuteInterval={30}
/>
<TouchableOpacity
style={styles.selectionButton}
onPress={() => setShowPicker(!showPicker)}
>
<Text style={styles.selectionButtonText}>{selectedValue}</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.submitButton}
onPress={handleSubmit}
>
<Text style={styles.submitButtonText}>Submit</Text>
</TouchableOpacity>
{showPicker && (
<Picker
selectedValue={selectedValue}
style={styles.picker}
onValueChange={(itemValue) => {
setSelectedValue(itemValue);
setShowButtons(itemValue !== 'Alege Specializarea');
}}
>
{options.map((option) => (
<Picker.Item
label={option}
value={option}
key={option}
/>
))}
</Picker>
)}
{showButtons && optionMapping[selectedValue].length > 0 && (
<View style={styles.buttonContainer}>
{optionMapping[selectedValue].map((buttonName) => (
<TouchableOpacity
style={[
styles.button,
buttonName === selectedDoctor && {
backgroundColor: '#24b6d4',
},
]}
key={buttonName}
onPress={() => setSelectedDoctor(buttonName)}
>
<Text
style={[
styles.buttonText,
buttonName === selectedDoctor && { color: 'white' },
]}
>
{buttonName}
</Text>
</TouchableOpacity>
))}
</View>
)}
</View>
<Modal
animationType="slide"
transparent={true}
visible={modalVisible}
>
<View style={styles.centeredView}>
<View style={styles.modalView}>
<Text style={styles.modalText}>
Your appointment has been scheduled for{' '}
{chosenDate.toString()} with {selectedDoctor}
</Text>
<TouchableOpacity
style={styles.modalButton}
onPress={() => setModalVisible(false)}
>
<Text style={styles.modalButtonText}>Close</Text>
</TouchableOpacity>
</View>
</View>
</Modal>
</>
);
};
const styles = StyleSheet.create({
container: {
top: -160,
flex: 1,
width: 350,
justifyContent: 'center',
},
image: {
alignSelf: 'center',
},
selectionButton: {
backgroundColor: 'lightgray',
padding: 10,
borderRadius: 10,
left: 20,
},
selectionButtonText: {
fontSize: 18,
},
picker: {
width: '100%',
},
buttonContainer: {
flexDirection: 'row',
justifyContent: 'center',
},
button: {
backgroundColor: '#fff',
borderWidth: 1,
borderColor: '#24b6d4',
borderRadius: 10,
padding: 10,
margin: 10,
width: 120,
},
buttonText: {
color: '#24b6d4',
fontSize: 18,
textAlign: 'center',
},
submitButton: {
backgroundColor: '#24b6d4',
borderRadius: 10,
padding: 10,
margin: 10,
},
submitButtonText: {
color: 'white',
fontSize: 18,
textAlign: 'center',
},
centeredView: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
marginTop: 22,
},
modalView: {
margin: 20,
backgroundColor: 'white',
borderRadius: 20,
padding: 35,
alignItems: 'center',
shadowColor: '#000',
shadowOffset: {
width: 0,
height: 2,
},
shadowOpacity: 0.25,
shadowRadius: 3.84,
elevation: 5,
},
modalText: {
marginBottom: 15,
textAlign: 'center',
},
modalButton: {
backgroundColor: '#24b6d4',
borderRadius: 10,
padding: 10,
margin: 10,
},
modalButtonText: {
color: 'white',
fontSize: 18,
textAlign: 'center',
},
});
export default App;
I use ExpoGO to "export" the project.
I tried many changes at firebase like: import firebase from 'firebase'; and all that changes for import firebase,none of that works but i tried with Firebase JS SDK and still dosent work.

Async Storage movie watchlist in React Native

its my first time i create an APP for my study project , i created app of database of movies using TMDB API , and it remain one last step to finish my project , and it's creating WatchList or Plan to Watch , and i have no idea how to make it . please can someone who have idea of how to create it with Async Storage or anything to save watchlist, and where to add it?
I will put my code
this code of Movie screen, and i need a touchableopacity that make save the movie into favorite component
import React, {useEffect, useState} from 'react';
import {
View,
Text,
Image,
Dimensions,
StyleSheet,
Linking,
ImageBackground,
TouchableOpacity,
ScrollView,
FlatList
} from 'react-native';
import {IMAGE_POSTER_URL} from '../config';
import {GET} from '../../Services/API';
import Loader from '../Components/Loader';
import Constants from '../Components/Constants';
import TrendingMovies from '../Components/TrendingMovies';
import TrendingPeople from '../Components/TrendingPeople';
import { createStackNavigator } from "#react-navigation/stack";
import PeopleDetails from '../Components/PeopleDetails.js';
import { LinearGradient } from 'expo-linear-gradient';
import {POSTER_IMAGE} from '../config';
import AsyncStorage from '#react-native-async-storage/async-storage';
const deviceHeight = Dimensions.get('window').height;
const deviceWidth = Dimensions.get('window').width;
const MovieDetails = props => {
const [loading, setLoading] = useState(true);
const [details, setDetails] = useState();
const [favourites, setFavourites] = useState([]);
useEffect(() => {
const getDetails = async () => {
const data = await GET(`/movie/${props.route.params.movieId}`);
setDetails(data);
setLoading(false);
};
getDetails();
}, []);
useEffect(() => {
const getVideo = async () => {
const results = await GET(`/movie/${props.route.params.movieId/videos}`);
setDetails(results);
setLoading(false);
};
getVideo();
}, []);
const getGenre = () => {
return details.genres.map(genre => (
<View >
<Text style={styles.genre}>{genre.name}</Text>
</View>
));
};
return (
<View style={styles.sectionBg}>
{loading ? (
<Loader />
) : (
<View style={{ flex: 1 }} >
<Image
source={{uri: `${IMAGE_POSTER_URL}${details.backdrop_path}`}}
style={styles.imageBg}
/>
<View style={{flexDirection:'row', justifyContent:'space-between', alignItems:'center', marginRight:15, marginTop:10}}>
<TouchableOpacity onPress={() => props.navigation.goBack()}
style={{ marginLeft:20, marginTop: 20, marginBottom:20}}
>
<Image
source={require("../../assets/icons/back.png")}
style={{ width:93/1.4 , height: 50/1.4 }} />
</TouchableOpacity>
<TouchableOpacity
style={{ marginLeft:20, marginTop: 20, marginBottom:20}}
>
<Image
source={require("../../assets/icons/nolicked.png")}
style={{ width:256/5.7 , height: 252/5.7 }} />
</TouchableOpacity>
</View>
<ScrollView style={{ flex:1 ,}} >
<TouchableOpacity onPress={() => {
Linking.openURL('https://www.youtube.com/watch?v=${details.key}');
}}
style={{ marginTop:240, marginLeft: "70%",zIndex:1 }}
>
<Image
source={require("../../assets/icons/youtube.png")}
style={{ width: 75, height: 75}} />
</TouchableOpacity>
<ImageBackground
source={require("../../assets/icons/hmm.png")}
style={{ width:'100%' , height: '84%',zIndex:-1 ,marginTop: -60,marginBottom:20}} >
<View style={{ alignSelf: 'center' , marginTop:40 }} >
<View style={{flexDirection: 'row' }} >
<Image
source={{uri: `${IMAGE_POSTER_URL}${details.poster_path}`}}
style={{ width: 150/1.2 , height: 220/1.2 , borderRadius: 20, marginTop: 40 , marginLeft: 20, zIndex:1 }} />
<View style= {{flexDirection:'column' , }} >
<Text style={styles.detailsMovieTitle}>{details.title}</Text>
<View style={{flexDirection: 'row' , alignItems: 'center', marginLeft: 15 , backgroundColor:'orange' , width:70, marginVertical: 5, borderRadius:10}} >
<Image
source={require("../../assets/icons/star.png")}
style={{ width: 20, height: 20 , marginLeft: 5, marginVertical:8}} />
<Text style= {{color:'#20222A' , fontSize: 18, marginLeft: 6, fontWeight:'bold' ,marginRight: 15}} >{details.vote_average}</Text>
</View>
<View style={{ flexDirection: 'row', width: 80 ,marginTop:25, marginLeft:20}}>
{getGenre()}
</View>
<Text style={{marginLeft: 14,
marginHorizontal:-5,
marginVertical:5,
fontWeight:'bold',
color: '#C3C3C3',
fontSize: 10,}}>{details.runtime} Minutes</Text>
<Text style={{marginLeft: 14,
marginHorizontal:-5,
color: '#C3C3C3',
fontWeight:'bold',
fontSize: 10,}}> Release Date: {details.release_date} </Text>
</View>
</View>
<View style={{marginLeft:15, zIndex:1 , marginBottom:50, marginLeft:20}} >
<Text style={{color:'white', fontSize:16, fontWeight:'bold' , marginBottom: 1,marginLeft: -5}} > Overview </Text>
<Text style={{color: 'white',
fontSize: 12, width:330, marginBottom:15}}>{details.overview}</Text>
<TrendingPeople
title="Actors"
navigation={props.navigation}
url={`/movie/${props.route.params.movieId}/credits`}
isForPage="details"
/>
<View style={{marginLeft: -15, marginTop:10, }} >
<TrendingMovies
title="SIMILAR MOVIES"
navigation={props.navigation}
url={`/movie/${props.route.params.movieId}/similar`}
/>
</View>
</View>
</View>
</ImageBackground>
</ScrollView>
</View>
)}
</View>
);
};
const styles = StyleSheet.create({
sectionBg: {
backgroundColor: Constants.baseColor,
height: deviceHeight,
flex:1
},
trendingPeopleImage: {
height: 70,
width: 70,
borderRadius: 500,
},
trendingPeopleName: {
width: 60,
color: Constants.textColor,
fontSize: 12,
textAlign: 'center',
marginTop: 10,
},
trendingPeopleContainer: {
margin: 10,
},
heading: {
fontSize: 12,
color: 'white',
margin: 10,
fontWeight:'bold'
},
posterImage: {
height: 800,
width: 150,
borderRadius: 10,
},
movieTitle: {
color: Constants.textColor,
width: 150,
textAlign: 'center',
marginTop: 5,
fontSize: 20,
fontWeight:'bold'
},
imageBg: {
position: 'absolute', top:0, left:0 ,
width: deviceWidth,
height: 400,
opacity: 0.8
},
detailsMovieTitle: {
fontSize: 20,
width: 180,
fontWeight:'bold',
color: 'white',
marginLeft:15,
marginTop: 35
},
linkContainer: {
backgroundColor: Constants.secondaryColor,
borderRadius: 100,
padding: 10,
width: 45,
marginLeft: 20,
marginTop: -20,
},
overview: {
color: 'white',
marginHorizontal: 10,
textAlign: 'justify',
fontSize: 16,
},
details: {
color: 'white',
fontSize: 11,
marginLeft: 10,
fontWeight: 'bold',
},
detailsContainer: {
display: 'flex',
marginLeft:15
},
genreContainer: {
borderColor: Constants.textColor,
paddingHorizontal: 0,
},
genre: {
width: 50,
marginHorizontal:-5,
fontWeight:'bold',fontWeight:'bold',
color: '#C3C3C3',
marginRight:4,
fontSize: 9,
},
image : {
height: 100,
width: 180,
borderRadius: 15,
paddingHorizontal: 5,
marginTop: 10,
marginLeft: 20
},
Text: {
marginLeft: 20,
color: 'white',
fontWeight: 'bold',
fontSize: 20
},
title: {
marginTop: 10,
width: 150,
textAlign: 'center',
color: 'white',
fontWeight: 'bold',
fontSize: 12
}
});
export default MovieDetails;```
First you create a favorite state
const [ favorites, setFavorites ] = useState([]);
Then you use useEffect to load the favorite from async storage.
const getData = async () => {
try {
const value = await AsyncStorage.getItem('#storage_key')
if(value !== null) {
setFavorites(JSON.parse('#storage_key'));
}
} catch(e) {
// error reading value
}
}
useEffect(() => {
getData();
}, [])
Then you create a touchable component to add to favorites.
<TouchableOpacity onPress={() => addToFavorites('some_id')}>
Add to Favorites
</TouchableOpacity>
Create the add to favorite function
const addToFavorites = async (id) => {
await AsyncStorage.setItem('#storage_key', JSON.stringify([...favorites, id]))
setFavorites([...favorites, id]);
}
More on Asyncstorage usage here - https://react-native-async-storage.github.io/async-storage/docs/usage

In react-native-gesture-handler/Swipeable how to add post API to it

Please Help.In react native expo. I am using react-native-gesture-handler Swipeable the problem is I am not getting it how to add the update status API here . once I swipe it to collect samples it should be stay constant to samples collected. I have used redux i put all my codes below
in my actions here I put the API URL
export const updateStatus = (collected) => {
return async (dispatch) => {
const token = await SecureStore.getItemAsync("userToken");
const url = `/update-status`;
var formdata = new FormData();
formdata.append("Booking_no", "");
formdata.append("action ", collected );
const response = await api
.post(url, {
headers: {
Authorization: `Bearer ${token}`,
},
})
.then((res) => {
return res;
})
.catch((error) => {
return error.response;
});
dispatch({
type: "UPDATE_STATUS",
payload: response,
});
};
};
in reducer
case "UPDATE_STATUS": {
if (action.payload.status === 200) {
let newState = {
...state,
updatestatus: true,
};
return newState;
} else {
let newState = {
...state,
updatestatus: false,
};
return newState;
}
}
in component
import React, { Component } from "react";
import {
StyleSheet,
Text,
View,
Image,
Linking,
ActivityIndicator,
ScrollView,
} from "react-native";
import MaterialCommunityIcons from "react-native-vector-icons/MaterialCommunityIcons";
import Swipeable from "react-native-gesture-handler/Swipeable";
import Sampleitems from "./Sampleitems";
import { fetchBookingDetails, updateStatus } from "../../../../../actions";
import { connect } from "react-redux";
import { TouchableHighlight } from "react-native-gesture-handler";
class Orderitems extends Component {
constructor(props) {
super(props);
this.state = {
showMe: true,
};
}
componentDidMount() {
this.props.fetchBookingDetails(this.props.route.params.booking_id);
setTimeout(() => {
this.setState({
showMe: false,
});
}, 3000);
}
render() {
const LeftSwipeActions = () => {
return (
<View style={[styles.container1, styles.horizontal]}>
{this.state.showMe ? (
<View style={{ alignSelf: "center" }}>
<ActivityIndicator size="large" color="#4DB2F8" />
</View>
) : (
<View style={styles.sampleMain}>
<Text style={styles.sample}>Samples Collected</Text>
</View>
)}
</View>
);
};
let bookingtest = this.props.bookinglist;
const items =
bookingtest && bookingtest.items && bookingtest.items.length > 0 ? (
bookingtest.items.map((booking_test) => {
return (
<Sampleitems
key={booking_test.id}
quantity={
booking_test && booking_test.test ? (
<View
style={{
borderRadius: 5,
borderWidth: 1,
borderColor: "#4D4D4D",
height: 30,
width: 30,
paddingTop: 5,
}}
>
<Text style={{ textAlign: "center", fontSize: 12 }}>
1 x
</Text>
</View>
) : null
}
test={
booking_test && booking_test.test ? (
booking_test.test.test_name
) : (
<View style={{ alignSelf: "center" }}>
<Text style={{ color: "#A1E1F3" }}>No Test Available</Text>
</View>
)
}
/>
);
})
) : (
<View style={{ alignSelf: "center" }}>
<Text style={{ color: "#A1E1F3" }}>No Test Available</Text>
</View>
);
const { navigation, family } = this.props;
let bookdata = this.props.family_data;
return (
<View style={styles.container} key={bookdata.id}>
<ScrollView>
<View style={{ margin: 15, marginBottom: 100, marginTop: 100 }}>
<View style={{ borderRadius: 10 }}>
<View style={{ padding: 20, backgroundColor: "white" }}>
<View
style={{ flex: 1, flexDirection: "row", paddingRight: 15 }}
>
<View
style={{
borderRadius: 5,
backgroundColor: "#4D4D4D",
height: 30,
width: 30,
paddingTop: 4,
}}
>
<Image
source={require("../../../../../assets/delivery/placeholder.png")}
resizeMode="contain"
tintColor="white"
style={{
height: 20,
width: 20,
alignSelf: "center",
}}
/>
</View>
<View style={{ paddingRight: 2, paddingLeft: 10 }}>
<Text style={{ fontWeight: "bold", color: "black" }}>
{bookdata && bookdata.family
? bookdata.family.name
: null}
</Text>
<Text style={{ fontSize: 12 }}>
{bookdata && bookdata.family
? bookdata.family.mobile
: null}
</Text>
<Text style={{ paddingBottom: 5, fontSize: 12 }}>
{bookdata && bookdata.family
? bookdata.family.adr_line_1
: null}
</Text>
<View style={{ flexDirection: "row" }}>
<TouchableHighlight
style={{ width: "130%" }}
underlayColor="transparent"
onPress={() => {
Linking.openURL(
`http://maps.google.com/?q=${
bookdata && bookdata.family
? bookdata.family.adr_line_1
: null
}`
);
}}
>
<View
style={{
backgroundColor: "#202877",
flexDirection: "row",
padding: 10,
paddingLeft: 0,
paddingRight: 0,
borderRadius: 7,
justifyContent: "center",
// width: "80%",
}}
>
<MaterialCommunityIcons
name="directions"
style={{ color: "white" }}
size={20}
/>
<Text
style={{
color: "white",
alignSelf: "center",
fontSize: 10,
paddingRight: 5,
}}
>
Get Direction
</Text>
</View>
</TouchableHighlight>
<TouchableHighlight
style={{ width: "150%" }}
underlayColor="transparent"
onPress={() => {
Linking.openURL(
`tel:${
bookdata && bookdata.family
? bookdata.family.mobile
: null
}`
);
}}
>
<View
style={{
backgroundColor: "#202877",
flexDirection: "row",
padding: 10,
borderRadius: 7,
paddingLeft: 0,
paddingRight: 0,
justifyContent: "center",
marginLeft: 40,
}}
>
<MaterialCommunityIcons
name="cellphone"
style={{ color: "white" }}
size={20}
/>
<Text
style={{
color: "white",
alignSelf: "center",
fontSize: 10,
paddingRight: 5,
}}
>
Call Now
</Text>
</View>
</TouchableHighlight>
</View>
</View>
</View>
</View>
</View>
<View style={{ borderRadius: 10, marginTop: 30 }}>
<View
style={{
flex: 1,
flexDirection: "row",
padding: 20,
backgroundColor: "#FAFAFA",
borderTopLeftRadius: 10,
borderTopRightRadius: 10,
}}
>
<Image
source={require("../../../../../assets/delivery/menu.png")}
resizeMode="contain"
style={{
width: 15,
height: 15,
alignSelf: "center",
}}
/>
<Text style={{ fontSize: 17 }}> Sample Items </Text>
</View>
<View style={{ padding: 20, backgroundColor: "white" }}>
{items}
</View>
</View>
</View>
</ScrollView>
{/* header */}
<View
style={{
flex: 1,
top: 0,
right: 0,
left: 0,
paddingTop: 35,
paddingBottom: 10,
position: "absolute",
backgroundColor: "white",
shadowColor: "black",
shadowOffset: {
width: 0,
height: 12,
},
shadowOpacity: 1,
shadowRadius: 16.0,
elevation: 2,
}}
>
<View
style={{
flex: 1,
backgroundColor: "white",
padding: 10,
flexDirection: "row",
}}
>
<MaterialCommunityIcons
style={{ alignSelf: "center" }}
name="chevron-left"
size={26}
onPress={() => navigation.goBack(null)}
/>
<Text
style={{
fontSize: 17,
fontWeight: "800",
alignSelf: "center",
paddingLeft: 40,
}}
>
#{bookdata.booking_no}
</Text>
</View>
</View>
{/* footer */}
<View
style={{
flex: 1,
bottom: 0,
right: 0,
left: 0,
position: "absolute",
}}
>
<Swipeable renderLeftActions={LeftSwipeActions}>
<View style={styles.collectMainMain}>
<MaterialCommunityIcons
name="chevron-right"
style={styles.material}
size={20}
/>
<View style={styles.collectMain}>
<Text style={styles.collect}>Collect Samples</Text>
</View>
</View>
</Swipeable>
</View>
</View>
);
}
_onLoadEnd = () => {
this.setState({
loading: false,
});
};
}
const mapStateToProps = (state) => {
return {
family_data: state.detailData.booking_details,
bookinglist: state.detailData.booking_details,
update_status: state.detailData.updatestatus,
};
};
export default connect(mapStateToProps, {
fetchBookingDetails,
updateStatus,
})(Orderitems);```
Don't check the status code on your reducer. you can easily check it on your api.post and then send a proper action to the reducer:
const response = await api
.post(url, {
headers: {
Authorization: `Bearer ${token}`,
},
})
.then((res) => {
return res.json();
})
.then(res => {
if(res.status === 200) {
dispatch({
type: "UPDATE_STATUS_SUCCESS",
})
} else {
dispatch({
type: "UPDATE_STATUS_FAILURE",
})
}
})
.catch((error) => {
console.log(error);
dispatch({
type: "UPDATE_STATUS_FAILURE",
})
});
Now, if the response status was 200, the proper action will be dispatched and if there is an error or the sample UPDATE_STATUS_FAILURE will be dispatched.
In the reducer:
// rest of the codes ...
case "UPDATE_STATUS_SUCCESS":
return{
...state,
updateStatus: true,
}
case "UPDATE_STATUS_FAILURE":
return{
...state,
updateStatus: false
}
// rest of the codes ...

Is it possible to change the width of just a top "header" thing using popup-menu in react native?

Using React Native react-native-popup-menu is it possible to style the menu, so it'll look something like this below?
I have this at the moment, with no clue how to make the above one:
Current code used for styling:
<MenuOptions optionsContainerStyle={{marginLeft: 70, marginTop: 10, backgroundColor: "lightgray", borderBottomLeftRadius: 10, borderBottomRightRadius: 10, borderTopLeftRadius: 20, borderTopRightRadius: 20}}>
<View style={{height: 200}}>
<ScrollView>
{state.data.map((item) => {
return (
<MenuOption
key={item["ArticleId"]}
onSelect={() => {
props.setBudTextCallBack(item["Name"])
}}
customStyles={
{
optionWrapper: {height: 30, backgroundColor: "silver", marginLeft: 5, marginRight: 5, marginTop: 5, marginBottom: 1},
optionText: {fontSize: 18, color: "#faf3ea"},
}
}
text={item["Name"]}
/>
);
})}
</ScrollView>
</View>
</MenuOptions>
Is it possible, to change somehow the width of just this top header "kategoria"?
Working example Link: https://snack.expo.io/#msbot01/fascinated-pretzels
Working example is given below
import React, { Component } from 'react';
import { Text, View, StyleSheet, Image } from 'react-native';
import Constants from 'expo-constants';
import { MenuProvider } from 'react-native-popup-menu';
import {
Menu,
MenuOptions,
MenuOption,
MenuTrigger,
} from 'react-native-popup-menu';
export default class NoApproval extends Component<Props> {
constructor(props) {
super(props);
this.state = {
color: 'orange'
}
}
render(){
return (
<MenuProvider>
<View>
<Text>Hello world!</Text>
<Menu style={{backgroundColor:'orange', height:60, alignItems:'center', margin:10, borderRadius:30, paddingLeft:20, flexDirection:'row'}} onBackdropPress={() => this.setState({color:'orange'})}>
<View style={{height:40, width:40, justifyContent:'center', alignItems:'center', borderWidth:2, borderRadius:30, borderColor:'white'}}>
<Image
style={{height:20,width:20}}
source={{uri: 'https://img.icons8.com/offices/344/folder-invoices.png'}}
/>
</View>
<MenuTrigger text='Kategoria' style={{backgroundColor:this.state.color, height:60, justifyContent:'center', marginLeft:5, borderTopLeftRadius:20, borderTopRightRadius:20, width:100, alignItems:'center'}} onPress={() => this.setState({color:'#d4d6d5'})}/>
<MenuOptions optionsContainerStyle={{marginTop:60, backgroundColor:'#d4d6d5', marginLeft:5, shadowOpacity: 0, shadowOffset: { width: 0, height: 0 }, shadowColor:'red'}}>
<MenuOption onSelect={() => alert(`Save`)} text='Save' style={{marginLeft:10}}>
<Text style={{color: 'white'}}>Save</Text>
</MenuOption>
<MenuOption onSelect={() => alert(`Delete`)} style={{marginLeft:10, }}>
<Text style={{color: 'white'}}>Delete</Text>
</MenuOption>
<MenuOption onSelect={() => alert(`Not called`)} disabled={true} text='Disabled' />
</MenuOptions>
</Menu>
</View>
</MenuProvider>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
padding: 8,
},
paragraph: {
margin: 24,
fontSize: 18,
fontWeight: 'bold',
textAlign: 'center',
},
});

React native - remove object from array

I have a Modal that displays a list of contacts. onPress, contacts are dynamically added to a View.
If a contact has already been added, on second onPress I would like to remove it from the View. For that I'm amending the state/array containing the contacts, using splice but it removes all the contacts at once.
I'm also trying to update the state of the 'Add' icon. If a contact has been added the Add icon Image should become the active one.
Not sure what I'm doing wrong?
Here's the Modal opened up:
My code:
import React, {Component} from 'react'
import {
Text,
View,
ListView,
ScrollView,
StyleSheet,
Image,
TouchableHighlight,
TextInput,
Modal,
} from 'react-native'
const friends = new ListView.DataSource({
rowHasChanged: (r1, r2) => r1 !== r2
}).cloneWithRows([
{
id: 1,
firstname: 'name1',
surname: 'surname1',
image: require('../images/friends/avatar-friend-01.png')
},
{
id: 2,
firstname: 'name2',
surname: 'surname2',
image: require('../images/friends/avatar-friend-02.png')
},
{
id: 3,
firstname: 'name3',
surname: 'surname3',
image: require('../images/friends/avatar-friend-03.png')
},
])
class AppView extends Component {
state = {
isModalVisible: false,
contactsPicked: [],
friendsState: {},
}
setModalVisible = visible => {
this.setState({isModalVisible: visible})
}
pickContact = (friend) => {
if(this.state.contactsPicked.indexOf(friend) < 0){
var tempFriendsState = this.state.friendsState
tempFriendsState[friend.id] = true
this.setState({
contactsPicked: [ ...this.state.contactsPicked, friend],
friendsState: tempFriendsState,
})
}
else{
let index = this.state.contactsPicked.indexOf(friend)
let nextContacts = this.state.contactsPicked
nextContacts.splice(index,1)
let tempFriendsState = this.state.friendsState
tempFriendsState[friend.id] = false
this.setState({
contactsPicked: nextContacts,
friendsState: tempFriendsState,
})
}
}
removeContact = (friend) => {
let index = this.state.contactsPicked.indexOf(friend)
let nextContacts = this.state.contactsPicked
nextContacts.splice(index,1)
this.setState({
contactsPicked: nextContacts,
})
}
_renderAddFriendTile = () => {
return(
<View style={[styles.step, styles.stepThree]}>
<View style={{flex:1}}>
<Text style={styles.heading}>Friend tile</Text>
</View>
{this.state.contactsPicked.length > 0 && (
<TouchableHighlight onPress={() => {this.removeContact(this.state.contactsPicked)}}>
<View>
{this.state.contactsPicked.map((contact,index) => (
<View key={index} style={[styles.row, styles.friendRow]}>
<Image source={contact.image} style={styles.friendIcon}></Image>
<Text style={styles.name}>{contact.firstname} </Text>
<Text style={styles.name}>{contact.surname}</Text>
<View style={styles.roundIconContainer}>
<View style={styles.roundIcon}>
<View style={[styles.removeButton, styles.buttonSmall]}>
<Image source={require('../images/button-cross-small.png')} style={styles.crossIconSmall}></Image>
</View>
</View>
</View>
</View>
))}
</View>
</TouchableHighlight>
)}
<TouchableHighlight style={styles.addFriendButtonContainer} onPress={() => {this.setModalVisible(true)}}>
<View style={styles.addFriendButton}>
<Text style={styles.addFriendButtonText}>Add friends</Text>
</View>
</TouchableHighlight>
</View>
)
}
render(){
return (
<ScrollView style={styles.container}>
<Modal
animationType={'fade'}
transparent={true}
visible={this.state.isModalVisible}
>
<View style={styles.addFriendModalContainer}>
<View style={styles.addFriendModal}>
<TouchableHighlight onPress={() => {this.setModalVisible(false)}}>
<View>
<Text>Close</Text>
</View>
</TouchableHighlight>
<ListView
dataSource={friends}
renderRow={(friend) => {
return (
<FriendRow
friend={friend}
pickContact={this.pickContact}
isSelected={this.state.friendsState[friend.id]}
/>
)
}}
/>
</View>
</View>
</Modal>
{this._renderAddFriendTile()}
</ScrollView>
)
}
}
class FriendRow extends Component {
render(){
return(
<TouchableHighlight onPress={() => {this.props.pickContact(this.props.friend)}}>
<View style={[styles.row, styles.friendRow]}>
<Image source={this.props.friend.image} style={styles.friendIcon}></Image>
<Text style={styles.name}>{this.props.friend.firstname} </Text>
<Text style={styles.name}>{this.props.friend.surname}</Text>
<View style={styles.roundIconContainer}>
<View style={styles.roundIcon}>
<View style={this.props.isSelected ? [styles.buttonActive, styles.buttonSmall]: [styles.modalButtonInactive, styles.buttonSmall]}>
<Image source={this.props.isSelected && require('../images/button-tick-small-on.png')} style={styles.buttonTickSmall}></Image>
</View>
</View>
</View>
</View>
</TouchableHighlight>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#e1e1e1'
},
row: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
},
step: {
backgroundColor: '#ffffff',
borderRadius: 4,
borderLeftWidth: 5,
flex: 1,
marginLeft: 10,
marginRight: 10,
marginBottom: 10,
paddingLeft: 15,
paddingRight: 10,
paddingTop: 15,
paddingBottom: 20,
shadowOffset: {
width: 0,
height: 2,
},
shadowRadius: 2,
shadowOpacity: 0.2,
shadowColor: '#000000',
},
stepThree: {
borderLeftColor: '#ffbd18',
},
heading: {
textAlign: 'center',
fontWeight: 'bold',
fontSize: 15,
color: '#333333',
},
addFriendButtonContainer: {
marginTop:15,
flex:1,
alignItems: 'center',
justifyContent: 'center',
flexDirection: 'row',
},
addFriendButton: {
backgroundColor: '#ffbd18',
width: 270,
borderRadius: 4,
paddingTop: 15,
paddingBottom: 15,
},
addFriendButtonText: {
color: '#ffffff',
fontSize: 18,
fontWeight: 'bold',
textAlign: 'center',
},
pickContainer: {
flex:1,
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
borderRightWidth: 1,
},
pickWrapper: {
flex: 1,
flexDirection: 'row',
justifyContent: 'space-around',
alignItems: 'center',
marginTop: 10,
},
buttonBig: {
height: 60,
width: 60,
borderRadius: 30,
},
buttonSmall: {
height: 20,
width: 20,
borderRadius: 10,
},
buttonActive: {
backgroundColor: '#fd6769',
alignItems: 'center',
justifyContent: 'center',
},
buttonInactive: {
backgroundColor: '#eeeeee',
alignItems: 'center',
justifyContent: 'center',
},
removeButton:{
backgroundColor: '#cccbcb',
alignItems: 'center',
justifyContent: 'center',
},
modalButtonInactive: {
backgroundColor: '#ffffff',
borderWidth: 1,
borderColor: '#eeeeee',
},
buttonTickBig: {
width: 34,
height: 28,
},
buttonTickMinusBig: {
width: 18,
height: 8,
},
buttonTickSmall: {
width: 12,
height: 10,
},
crossIconSmall: {
width: 12,
height: 10,
},
pickText: {
color: '#c7c7c7',
fontWeight: 'bold',
},
addFriendModalContainer: {
flex: 1,
},
addFriendModal: {
flex: 1,
backgroundColor: '#ffffff',
borderRadius: 4,
paddingLeft: 15,
paddingRight: 10,
paddingTop: 20,
paddingBottom: 20,
shadowOffset: {
width: 0,
height: 2,
},
shadowRadius: 2,
shadowOpacity: 0.2,
shadowColor: '#000000',
textAlign: 'center',
},
nextButtonContainer: {
marginBottom: 20,
},
nextButton: {
textAlign:'right',
},
friendRow: {
height: 60,
borderBottomWidth: 1,
borderBottomColor: '#eeeeee',
justifyContent: 'flex-start',
},
friendIcon: {
width: 50,
height: 50,
marginRight: 25,
},
roundIconContainer:{
flex: 1,
flexDirection: 'row',
justifyContent: 'flex-end',
alignItems: 'flex-end',
},
roundIcon: {
height: 20,
width: 20,
borderRadius: 10,
backgroundColor: '#fd6769',
justifyContent: 'center',
alignItems: 'center',
marginRight: 20,
},
})
export default AppView
'using splice but it removes all the contacts at once.'
Because you're using splice method wrong. Check the parameters the method gets.
http://www.w3schools.com/jsref/jsref_splice.asp
[ ...this.state.contactsPicked, this.state.contactsPicked.splice(friend)]
this doesn't work as you expected as well. It merges two arrays.
var parts = ['shoulders', 'knees'];
var parts2 = ['shoulders'];
var lyrics = [ ...parts, ...parts2 ];
console.log(lyrics)
It seems you don't have to use spread operator([...arr,.arr2]),
you can simply do that
Since it re creates subs every time modal's visiblity changes and even if you change state of parent component's state it does not re render subs so you need to keep internal state for you sub components
Also your _renderAddFriendTile method was working wrong too. When
you take a look at it carefully you will realize your mistake.
Don't forget to change your icons with my test icons
class AppView extends Component {
constructor(props) {
super(props);
this.state = {
isModalVisible: false,
contactsPicked: [],
friendsState: {},
}
}
setModalVisible = visible => {
this.setState({isModalVisible: visible})
}
pickContact = (friend) => {
if(this.state.contactsPicked.indexOf(friend) < 0){
var tempFriendsState = this.state.friendsState
tempFriendsState[friend.id] = true
this.setState({
contactsPicked: [ ...this.state.contactsPicked, friend],
friendsState: tempFriendsState,
})
}
else{
let index = this.state.contactsPicked.indexOf(friend)
let nextContacts = this.state.contactsPicked
nextContacts.splice(index,1)
let tempFriendsState = this.state.friendsState
tempFriendsState[friend.id] = false
this.setState({
contactsPicked: nextContacts,
friendsState: tempFriendsState,
})
}
}
removeContact = (friend) => {
let index = this.state.contactsPicked.indexOf(friend)
let nextContacts = this.state.contactsPicked
let tempFriendsState = this.state.friendsState
tempFriendsState[friend.id] = false
nextContacts.splice(index,1)
console.log('removeContact'+friend.id);
this.setState({
contactsPicked: nextContacts,
friendsState: tempFriendsState,
})
}
_renderAddFriendTile = () => {
return(
<View style={[styles.step, styles.stepThree]}>
<View style={{flex:1}}>
<Text style={styles.heading}>Friend tile</Text>
</View>
{ (this.state.contactsPicked.length) > 0 ?
this.state.contactsPicked.map((contact,index) => (
<TouchableHighlight onPress={() => {this.removeContact(contact)}}>
<View>
<View key={index} style={[styles.row, styles.friendRow]}>
<Image source={contact.image} style={styles.friendIcon}></Image>
<Text style={styles.name}>{contact.firstname} </Text>
<Text style={styles.name}>{contact.surname}</Text>
<View style={styles.roundIconContainer}>
<View style={styles.roundIcon}>
<View style={[styles.removeButton, styles.buttonSmall]}>
<Image source={require('./images/redtree.jpg')} style={styles.crossIconSmall}></Image>
</View>
</View>
</View>
</View>
</View>
</TouchableHighlight>
))
: null
}
<TouchableHighlight style={styles.addFriendButtonContainer} onPress={() => {this.setModalVisible(true)}}>
<View style={styles.addFriendButton}>
<Text style={styles.addFriendButtonText}>Add friends</Text>
</View>
</TouchableHighlight>
</View>
)
}
render(){
return (
<ScrollView style={styles.container}>
<Modal
animationType={'fade'}
transparent={true}
visible={this.state.isModalVisible}
>
<View style={styles.addFriendModalContainer}>
<View style={styles.addFriendModal}>
<TouchableHighlight onPress={() => {this.setModalVisible(false)}}>
<View>
<Text>Close</Text>
</View>
</TouchableHighlight>
<ListView
dataSource={friends}
renderRow={(friend) => {
return (
<FriendRow
friend={friend}
pickContact={this.pickContact}
isSelected={this.state.friendsState[friend.id]}
/>
)
}}
/>
</View>
</View>
</Modal>
{this._renderAddFriendTile()}
</ScrollView>
)
}
}
class FriendRow extends Component {
constructor(props) {
super(props);
this.state = {
isSelected:this.props.isSelected,
}
}
componentDidMount(){
console.log('didmount');
}
render(){
var imageSource = (this.state.isSelected==true) ? require('./images/tree.jpg') : ''
console.log('friend'+!this.props.isSelected)
return(
<TouchableHighlight onPress={() => {this.props.pickContact(this.props.friend);this.setState({isSelected:!this.state.isSelected})}}>
<View style={[styles.row, styles.friendRow]}>
<Image source={this.props.friend.image} style={styles.friendIcon}></Image>
<Text style={styles.name}>{this.props.friend.firstname} </Text>
<Text style={styles.name}>{this.props.friend.surname}</Text>
<View style={styles.roundIconContainer}>
<View style={styles.roundIcon}>
<View style={this.state.isSelected ? [styles.buttonActive, styles.buttonSmall]: [styles.modalButtonInactive, styles.buttonSmall]}>
<Image source={imageSource} style={styles.buttonTickSmall}></Image>
</View>
</View>
</View>
</View>
</TouchableHighlight>
)
}
}
You can use filter method to filter out contacts if it's already there in view.
To remove contacts from view if already added:
this.setState({
...state,
contactsPicked: this.state.contactsPicked.filter((contactsPicked,index)=> index != pickedContactsIndex)
})

Categories