0

Im new to react and try to understand better java script code.

I use the code below and it works: Basically, the function takes the previous state of the "description" and updates the "description" with the new value when the user enters something.

However, I don't quite understand how this is done in the code and I would appreciate an explanation (particularly regarding "=>", and "PrevState" and the interplay of both).

onChangeDescription(e) {
    const description = e.target.value;

    this.setState(prevState => ({
      currentTutorial: {
        ...prevState.currentTutorial,
        description: description
      }
    }));
  }

I also want to log the user input with () => console.log(this.state)) but I didnt found the right "place" to insert it in the above function.

dan_boy
  • 1,735
  • 4
  • 19
  • 50
  • I'm not sure what information you're asking for. Are you wondering about the syntax of [arrow functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions)? – Nicholas Tower May 05 '20 at 14:17
  • https://en.reactjs.org/docs/hooks-reference.html#functional-updates – Rashomon May 05 '20 at 14:19

1 Answers1

1

setState in react is an async process, so when your new state is dependent on the value of previous state then react suggest to use this callback format, where you get the last present value in state.

Regarding console, use below

    this.setState(prevState => ({
      currentTutorial: {
        ...prevState.currentTutorial,
        description: description
      }
    }), () => console.log(this.state)));

Read more about it here https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous

Milind Agrawal
  • 2,724
  • 1
  • 13
  • 20