Problem with updating state in react native component - react-native

I have an array with values i want to present and then if the user press the edit button the presentation is changed to a list of TextInput components. When done editing the user can press Save or Cancel. If Cancel is pressed the values in the textInput fields should not be saved to the original array of values.
My problem is that even when pressing Cancel the data in the original array seems to be updated.
This is the code:
`
const handlePress = (text, index) => {
const newSchedule = [...scheduleTempState]
newSchedule[index].value = text
setScheduleTempState(newSchedule)
}
const handlePress2 =()=>{
setScheduleTempState([]);
console.log("handlepress2")
setEdit(false)
}
const handlePress3 =()=>{
setScheduleTempState(scheduleState);
console.log("handlepress3")
setEdit(true)
}
return (
edit
?
<View style={styles.scheduleRow}>
<View style={styles.buttonView}>
<TouchableOpacity onPress = { ()=>{saveSchedule(projectId,scheduleState);updateClient() ;setEdit(false)}} >
<MaterialIcons name="save" size={16} color="green" />
</TouchableOpacity>
<TouchableOpacity onPress = { ()=>{handlePress2()}} >
<MaterialIcons name="cancel" size={16} color="red" />
</TouchableOpacity>
</View>
<View>
<FlatList
horizontal = {true}
data={scheduleTempState}
keyExtractor={item => item.id}
renderItem={({item, index}) => {
return (
<View style={styles.decimalInputView}>
<TextInput
style={styles.cellInput}
onChangeText={(text) => {handlePress(text, index)}}
value = {item.value} />
</View>
)
}}
/>
</View>
</View>
:
<View style={styles.scheduleRow}>
<View style={styles.buttonView}>
<TouchableOpacity onPress = { ()=>handlePress3()} >
<MaterialIcons name="edit" size={14} color="black" />
</TouchableOpacity>
</View>
<View >
<FlatList
horizontal={true}
data={scheduleState}
renderItem={renderScheduleItem}
keyExtractor={item => item.id}
/>
</View>
</View>
);
}`
I guess my problem has something to do with states not being updated, but i can not see how the edited values can be saved when i press cancel.

Problem:
You are updating the scheduleTempState by referencing your scheduleState. So when you mutate scheduleTempState, it also mutates the scheduleState.
Solution: Please use spread operator to scheduleState which can help to create a new copy of a reference.
const handlePress3 =()=>{
setScheduleTempState([...scheduleState]);
...
}
Suggestion: It would be better to use explanatory names for function. It will make the code more readable. For example:
onChangeText() instead of handlepress()
onCancelEditing() instead of handlepress2()
onEdit instead of handlepress3()
Hope you will get the idea.

Related

How to show an icon on last index of flat list

I'm trying to wrap my flat list and trying to show an Icon after last index of Flatlist. I had tried but it works fine on a single row. when we data goes to next row it would not work.
Here is my flat list code. Modal and Input both are my custom component.
const renderItem = ({item}) => {
return (
<TouchableOpacity style={[styles.tagPostContainer, styles.viewTagContainer]}>
<AppText
type={'input'}
label={`#${item}`}
color={colors.placeholder}
containerStyle={[styles.tagPostInactiveTxt, styles.BgAddedTag]}
/>
</TouchableOpacity>
);
};
return(
<>
<View style={{flexDirection:'row',justifyContent:'flex-start'}}>
<FlatList
data={tags}
renderItem={renderItem}
keyExtractor={keyExtractor}
contentContainerStyle={styles.TagFlatlist}
/>
<TouchableOpacity
style={styles.plusIconContainer}
onPress={() => setVisible(true)}>
<CreateBuildIconFocus height={13} width={13} />
</TouchableOpacity>
</View>
<Modal
visible={visible}
buttonLabel={'Done'}
containerWidth={width / 1.7}
onCancel={onCancel}
onSubmit={onClick}
containerHeight={Platform.OS === 'android' ? 200 : 200}>
<Input
placeholder={'Add Tags'}
autoFocus={true}
minWidth={120}
maxWidth={150}
value={tag}
onChangeText={text => setTag(text)}
/>
</Modal>
</>
)
FlatList styles:
TagFlatlist: {
flexDirection: 'row',
flexWrap: 'wrap',
alignItems: 'center',
},
Here is my design screen.
I find a solution for this. You can implement ListFooterComponent that used for showing something on end of flatlist. Here you can see more details of ListFooterComponent.
Here are the code of Flatlist.
return(
<FlatList
data={tags}
renderItem={renderItem}
keyExtractor={keyExtractor}
ListFooterComponent={
<TouchableOpacity
style={styles.plusIconContainer}
onPress={() => setVisible(true)}>
<CreateBuildIconFocus height={13} width={13} />
</TouchableOpacity>
}
contentContainerStyle={styles.TagFlatlist}
/>
)

React onPress execute immediately ( render time) , but once replace with arrow function it does not work

export const Focus = ({addSubject})=>{
const [tempValue, setTempValue] = useState(null);
return(
<View style={styles.container}>
<View style={styles.titleContainer}>
<Text style={styles.title}> What are you going to focus on....?</Text>
<View style={styles.inputcontainer}>
<TextInput style ={{flex:1, marginRight:10}}
onSubmitEditing ={
({nativeEvent}) => {
setTempValue(nativeEvent.text+'0000')
}
}
/>
<RoundedButton title ='+' onPress={
addSubject(tempValue)
}/>
</View>
</View>
</View>
);
}
Just after entering data, once hit the 'return' it submit entered "text+0000"
but once replace with
<RoundedButton title ='+' onPress={
()=>{ addSubject(tempValue)}
}/>
on press is not working
*** I'm testing this on on Expo web
What is the reason for this behavior and what is the solution to make it work once press the button.
Try without braces, then only it will return the addSubject function
<RoundedButton
title ='+'
onPress={()=> addSubject(tempValue)}
/>

React Native Collapse list with button

I'm making an app with expo react native, and I made a collapse that shows profile information about all users on my SQLite database.
I added a button (touchableopacity) inside the collapse and my idea is to edit information in the input where I'm showing information, but i don't know how to link the button press to the profile where is being touched.
so my code is as follows (i deleted styles to make it cleaner to see):
render(){
const miLista = this.state.datos.map((item) => //this is "list" and it works(show information of each profile and shows the button of each profile when i open the collapse of each on of them)
<ScrollView style={styles.container}>
<Collapse>
<CollapseHeader>
<Text>{item.id} {item.nombre}</Text> //here shows id and name (from sqlite data)
</CollapseHeader>
<CollapseBody >
<View key={item.id} >
<Text >Nombre</Text>
<TextInput
value={item.nombre}
onChangeText={(val) => this.setState({ nombre: val})}/>
<Text style=>Rut</Text>
<TextInput
value={item.rutPersona}
onChangeText={(val) => this.setState({ rutPersona: val})}/>
<Text >Clave</Text>
<TextInput
value={item.clave}
onChangeText={(val) => this.setState({ clave: val})}/>
{this.boton(item.id)}
</View>
</CollapseBody>
</Collapse>
</ScrollView>
);
return(
<View >
<SafeAreaView >
<TouchableOpacity
onPress={() => this.props.navigation.openDrawer()}>
<FontAwesome5 name="bars" size={24} color="#161924"/>
</TouchableOpacity>
</SafeAreaView>
<Text>Perfiles</Text>
<ScrollView>
{miLista}
</ScrollView>
</View>
);
};
so i needed to add .bind to the onpress of my button and pass the data: like this
boton(id,nombre,rutPersona,clave){
return(
<TouchableOpacity
key={id}
style={styles.boton}
onPress={this.funcionBoton.bind(this,nombre,rutPersona,clave,id)}
>
<Text>SAVE </Text>
</TouchableOpacity>
);
};

How to make specific component functional in a flatlist?

I am making an app where anyone can join a fantasy golf tournament. On my homepage there is a flatlist which is receiving data from api. There will be many tournaments but the user can only join the upcoming one. Now what i want to do is disable the functionality of every other tournament that means there is a join button through which user can join so i want to disable every other button and only enable the upcoming tournament button. What should i do?
here's my code
const Item = ({ title, location, date, Id }) => (
<View style={styles.renderItemView}>
<View style={styles.imageView}>
<Image style={styles.imageView2} source={require('../../assets/golf.png')} />
</View>
<View style={styles.TextView}>
<Text style={styles.Text}>Name: {title}</Text>
<Text style={styles.Text}>Location: {location}</Text>
<Text style={styles.Text}>StartDate: {moment(date).format('DD-MM-YYYY')}</Text>
<Text style={styles.Text}>Contest Fee: $49</Text>
</View>
<View style={styles.JoinView}>
<TouchableOpacity onPress={() =>{
navigation.navigate('Join', {key:Id, date});
}} style={styles.Touch1}>
<Text style={styles.JoinText}>Join</Text>
</TouchableOpacity>
</View>
</View>
);
const renderItem = ({ item }) => (
<View>
<Item title={item.name} location={item.location} date={item.startDate} Id={item.Id} />
</View>
);```
You could use row index and modulus operator to define the disabled prop like this:
const renderItem = ({ item, index }) => (
<View>
<Item title={item.name} disabled={index % 1 === 1} location={item.location} date={item.startDate} Id={item.Id} />
</View>
);`
And the use it in the Item component on the TouchableOpacity like this:
const Item = ({ disabled }) => (
<View>
...other stuff
<TouchableOpacity disabled={disabled} />
</View>
)
<TouchableOpacity disabled={props.disabled} />

I have passed component as argument, now how to render the component?

Below in a code I have describe the question as comment
//This is MessagesScreen.js
<FlatList
data={messages}
keyExtractor={messages => messages.id.toString()}
renderItem={({ item }) =>
<ListItem style={styles.listItem}
title={item.title}
subTitle={item.description}
image={item.image}
DeleteIconView={ListItemDeleteAction} /*Here ListItemDeleteAction.js
is component want to pass it to
the ListItem.js. Note: I have
imported all the nessory
labries*/
onPress={() => handleDelete(item)}
//renderRightActions={ListItemDeleteAction}
/>
}
ItemSeparatorComponent={ListItemSeparator}
refreshing={refreshing}
onRefresh={() => {
setMessages([
{
id: 2,
title: 'Komail',
description: 'React-Native Developer',
image: require("../asserts/komail.jpg"),
}
])
}}
/>
This is ListItemDeleteAction.js, which I want to render in ItemList.js
//This is ListItemDeleteAction.js
function ListItemDeleteAction(props) {
return (
<View style={styles.container}>
<MaterialCommunityIcons name="trash-can" size={30} color={Colors.danger} />
</View>
);
}
Now, in ListItem.js I want to render the ListItemDeleteAction.js as I have passed as a argument. Below in code I have described as comment.
Note: I am strict to this method, render the ListItemDeleteAction as it passed as argument, which is "DeleteIconView" as parameter in ListItem.js
function ListItem({ image, title, subTitle, ImageComponent, style, onPress, DeleteIconView}) {
return (
<TouchableHighlight
//onPress={onPress}
underlayColor={Colors.light}
>
<View style={[styles.container, style]}>
{ImageComponent}
{image && <Image style={styles.image} source={image} />}
<View style={styles.parentDeatailContainer}>
<View style={styles.detailContainer}>
<Text style={{ fontWeight: "bold" }}>{title}</Text>
{subTitle && <Text>{subTitle}</Text>}
</View>
<TouchableOpacity style={styles.deleteIconContainer} onPress={onPress}>
{DeleteIconView} /* This is the place where I want to render the
ListItemDeleteAction components as I passed as argument but How? */
</TouchableOpacity>
</View>
</View>
</TouchableHighlight>
);
}
You are passing the prop wrong. When you write DeleteIconView={ListItemDeleteAction}, you aren't actually creating a JSX component. This can be solved by writing the following.
renderItem={({ item }) =>
<ListItem style={styles.listItem}
title={item.title}
subTitle={item.description}
image={item.image}
DeleteIconView={<ListItemDeleteAction />}
onPress={() => handleDelete(item)}
/>
}
Now, the prop DeleteIconView is an actual JSX component which can be rendered as usual.