S
S
sharkdest2019-01-09 12:27:11
JavaScript
sharkdest, 2019-01-09 12:27:11

How to properly overwrite state value?

Hello,
here is my state:

this.state = {
...
 checkboxes: {
   a: true,
   b: true
 }
};

this is how I try to change the state:
...
this.setState({
 checkboxes[e.target.value]= !state
});

and as a result I get Syntax error:
5c35be069e42f369201472.png
Please tell me what I'm doing wrong.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Proskurin, 2019-01-09
@sharkdest

You need to get your object, change the field and send back in setState
1) via object cloning

let checkboxes= Object.assign({}, this.state.checkboxes); // Создаем копию, можно просто ссылку взять, но копию безопаснее
checkboxes[e.target.value] = false; // изменяем поле
this.setState({checkboxes}); // Сохраняем

2) through the spread operator
this.setState({
    checkboxes: {
          ...this.state.checkboxes,
          [e.target.value]: false // измененное поле объекта checkboxes
    }
})

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question