0

I have just tried to add value to this.state from browser console in React.

I tried it in two way,

first: used this code $r.state.list[0].a = 2.

second: used react developer extension and changed it from components.

this is the code I'm using:

this.state = {
  list: [
    { a: 5 },
    { b: 6 },
    { c: 1 },
  ],
}; 

the UI is working based on the state value. If I change the value it would be updated in UI.

I want to change the value from the console and check the UI is changing or not based on the value. If I hard code it will work.

Ali
  • 1,326
  • 1
  • 17
  • 38

1 Answers1

1

You should use setState function instead of mutating state directly you should do:

this.setState({newVal: 5});

and not this.state = {newVal: 5};

The reason you have to use setState and not change it directly is mainly because setState causes rerendering (if nessacry) and changing directly on state object does not.

In addition, notice this.setState is async!! That's way you might not see changes in state if printing it next line

You can though printing state inside render function or you can use the callback of setState ->

this.setState({newVal: 5}, (newState) => console.log(newState));
Shachar
  • 54
  • 3