Reputation: 39
I added a new object of contact and trying to show it in SectionList. But when I trying to put an object to array I'm getting an error: TypeError: undefined is not an object (evaluating 'n.data.length')
I used the instructions in this link to solve the problem. how to add a new object as a value to an array in the react state
constructor(props) {
super(props);
this.state = {
contacts : [],
newContactDialogVisible: false,
contactName : '',
contactPhone : ''
}
}
refreshContactsList = () => {
const newContact = {'name': this.state.contactName, 'phone': this.state.contactPhone};
Alert.alert(newContact.name + " " + newContact.phone); // Alert working and shows the right data
this.setState({ contacts: [...this.state.contacts, newContact] });
}
<SectionList
sections={this.state.contacts}
renderItem={({item, index, section}) => <Text key={index}>{item}</Text>}
/>
Upvotes: 1
Views: 970
Reputation: 39
Finally I found the right syntax of how to it:
refreshContactsList = () => {
const newContact = {data: [{name:this.state.contactName, phone:this.state.contactPhone}]};
this.setState({ contacts: [...this.state.contacts, newContact]})
}
Upvotes: 1
Reputation: 459
You didn't use the solution of the link correctly. Missing wrapping brackets.
this.setState(state => ({
contacts: [...state.contacts, newContact]
}));
I think you can go shorter with
this.setState({ contacts: [...this.state.contacts, newContact] });
And I would like to add that
this.refreshContactsList = this.refreshContactsList.bind(this);
is not necessary since refreshContactList
is an arrow function and you won't lose this
pointer inside. If you declare it as refreshContactList() {...}
you need to bind this
.
Upvotes: 1
Reputation: 801
I think the issue is with the wrong arrow function syntax. Try this
this.setState(state => {
return {contacts: [...state.contacts, newContact]};
});
Upvotes: 0