Not clear why code isn't working

So I’m doing the React Course and got to " Create a Controlled Input -

I originally wrote my handleChange() function as:

  this.setState(state =>({

which didn’t work. I got a hint and changed the method to:


Which works fine. However, I don’t really understand why my first code didn’t. Can anyone explain? Thanks in advance

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

Thanks, totallynotabot ArielLeslie.

setState() (documentation) in react can be used two ways (maybe more, I remember two).

One way is:

setState({objectKey: value})

This will try to update current state with returned object. It is NOT a callback function.

Second way is:

setState(callbackFunction(event, state, whatever){return ({objectKey: objectValue})})

When you will use arrow notation those two ways can get messed up. Try to write full callback function and trim it from there (that made me understand it).

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.