I have a state variable dataSource that has some data in it.
In a parent component I have the following:
updateFeed = newItem => {
this.setState({ dataSource: this.state.dataSource.data.unshift(newItem) })
console.log(this.state.dataSource.data)
}
render() {
console.log(this.state.dataSource.data)
return (
<React.Fragment>
<Header />
<Route
path="/"
exact
component={props => (
<Feed {...props} feedData={this.state.dataSource.data} updateFeed={this.updateFeed} />
)}
/>
<Route path="/profile/:id" exact component={props => <Profile {...props} />} />
</React.Fragment>
)
}
updateFeed is called from the child component.
onSubmit = () => {
const newPost = newData // some new data
this.props.updateFeed(newPost)
}
The updateFeed function is getting executed on submit, and the console.log is giving the updated data. But inside the render function this.state.dataSource.data is undefined. What am I missing here?
unshift? that mutate your state, which should be avoid.[newItem, ...this.state.dataSource.data]instead. If you mutate your state, your setState would not correctly working.