Alright so I am building this CRUD app with a React driven U/I. I'm having an issue with my state updating. Below are the code snippets that are involved in the problem. I've tried figuring it out myself and think it's that my state is updating correctly but it gets sent to the server before the state can be updated and when my component remounts it gets the old state from the server and overwrites the new one. The server always gets a state that is n - 1 to the actual number of items. Also if you know any ways that i could improve, please let me know I feel like this is a lot of work to do just 3 tasks!
Thank you in advance.
My state
this.state = {
newItem:{},
todos:[]
}
The retrieval methods
componentDidMount(){
this.getTodos(this.props);
}
getTodos(props){
axios.get(process.env.REACT_APP_SERVER+`/${props.match.params.id}/todos`)
.then(
(res)=>{
this.setState({todos:[...res.data]});
}
)
}
My creation and update methods
handleOnChange(e){
this.setState({newItem:{title:e.target.value, complete:false}});
}
addNewItem(){
this.setState({todos:[...this.state.todos, this.state.newItem]});
this.updateTodoList(this.props);
}
updateTodoList(props){
axios.put(process.env.REACT_APP_SERVER+`/${props.match.params.id}/todo/add`, this.state.todos).then(res=>{
console.log(res.data);
});
}
Update: Oh snap! That is what I figured, you've fixed my bug!