I have a todo list and after adding an item to it in the child component the change is not reflected straight away. I have to manually reload the page to see the change.The structure is something like this.
ToDo(Parent Componenet)
-> Todoi(Child Component)
I am updating data in the child component but as I said earlier it is not reflecting the change unless I reload the page manually. If I can somehow change the state in parent component through child component then the component will reload itself but I am not able to do it. Here is the part where I am updating the list.
const handleList= (e) => {
e.preventDefault();
console.log(e);
console.log(addtodo);
axios.post('/list',{
data:addtodo,
userid:username
}).then(function(res){
if(res.data === "ToDo Updated"){
navigate(`/todo/${username}`);
}
});
}
What should I do to make it?
You can either pass the state setter to your child component and then add the new entry in your post function:
const handleList= (e) => {
e.preventDefault();
console.log(e);
console.log(addtodo);
axios.post('/list',{
data:addtodo,
userid:username
}).then(function(res){
if(res.data === "ToDo Updated"){
setList(prevState => prevState.concat(addtodo));
}
});
}
<YourComponent setList={setList}/>
Or you can add a callback function prop to your component which is executed on successful request like so:
const handleList= (e) => {
e.preventDefault();
console.log(e);
console.log(addtodo);
axios.post('/list',{
data:addtodo,
userid:username
}).then(function(res){
if(res.data === "ToDo Updated"){
onSuccess(addtodo)
}
});
}
<YourComponent onSuccess={(todo)=>setList(prevState => prevState.concat(todo))}/>
I'm not sure what your state/data type looks like but I hope this helps!
Usually, a react component will be rerendered under two situations:
Therefore, we could manually trigger the status change of the parent component in the child component or update the server response as the props of the parent component.
I don't know how you handle your data in the parent component, but I guess you might need to make React detect your data updating.