2

I am trying to check my todo list and change the status but I cannot figure out what's wrong.

Here is my code:

handleChange = (id) => {
    let data = [...this.state.data];
    let indexOfTodo = data.findIndex(todo => todo.id === id);
    data[indexOfTodo].checked = !data[indexOfTodo].checked;
    console.log(data[indexOfTodo]);
    console.log(data)
}

I hit the button twice and here is the console.log

enter image description here

Sorry for dummy question. I am new in react

3
  • 1
    Were are you telling React to update?, normally this is with setState. Commented Oct 26, 2018 at 10:12
  • I know but before setState I want to check the data is updated correctly Commented Oct 26, 2018 at 10:37
  • I'd recommend to read beta.reactjs.org/learn/updating-arrays-in-state Commented Dec 6, 2022 at 9:52

2 Answers 2

3

You don't want to mutate the data[indexOfTodo] object, but instead create a copy of it with the checked property changed.

You must also put the updated array in state with setState for your component to re-render. You can use the function version of setState since your update is derived from data that is in your state.

handleChange = id => {
  this.setState(previousState => {
    let data = [...previousState.data];
    let indexOfTodo = data.findIndex(todo => todo.id === id);

    data[indexOfTodo] = {
      ...data[indexOfTodo],
      checked: !data[indexOfTodo].checked
    };

    return { data };
  });
};
Sign up to request clarification or add additional context in comments.

3 Comments

previousState is the best practice when calling setState?
If your state update is derived from data that is already in your state (like your example), it is best to give a function to setState that uses the previous state and returns the state update, yes. If it is not derived from data already in the state you can use an object, like e.g. onChange = (event) => { this.setState({ value: event.target.value }); }.
Thanks alot Tholle
0

There is nothing wrong with your code but to reflect the value in the state you need to call setState method.

You can use the below code:

handleChange= (id) => {
    let a = this.state.data[id].checked;
    let todo = update(this.state.data, { [id]: { checked: { $set: !a } } })
    this.setState({ data: todo });
}; 

To use update function. Need to import immutable helper:

import update from 'immutability-helper'; 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.