I am Passing a function from Parent component to child component and then calling that function in child component to update the state of parent component.
In Parent component:
const [todos, setTodos] = useState([]);
const updateTodoInUiAfterEdit = (updatedTodo, todoIdOfEdited)=>{
var temp = todos;
for(var i = 0; i < temp.length; i++){
if(temp[i].todo_id === todoIdOfEdited){
temp[i].description = updatedTodo;
break;
}
}
setTodos(temp);
console.log(todos);
}
It is logging the updated state here correctly, but UI is not updating as per latest state
3
Answers
The following code works:
setTodos
is an asynchronous function, which means that the state updates will not take effect immediately.For tackling it you have to update the setTodo by using its previous state as an argument.
Here’s helping code:
Upvote if it helps.. 🙂
The problem is, you are directly changing the state, which is wrong.
Do not mutate the state directly
See the updated code:
PS: Use let/const instead of var.