0

I am trying to update a key/value pair of a nested object in the state while the user types in the form. My state looks like this :

constructor(props) {
super(props);
this.state = {
  details: {
    detail1: {
      title: "",
      description: "",
      image1: null,
      image2: null,
    },
    detail2: {
      title: "",
      description: "",
      image1: null,
      image2: null,
    },
   detail3: {
      title: "",
      description: "",
      image1: null,
      image2: null,
    },
  },
};

}

This is my render method :

<form>
      <input
        type="text"
        value={this.state.creatives.creative1.title}
        onChange={(e) => {
          this.setState((prevState) => ({
            creatives: {
              ...prevState.creatives,
              creative1: {
                ...prevState.creatives.creative1,
                title: e.target.value,
              },
            },
          }));
          console.log(this.state.details.detail1.title);
        }}
      ></input>
    </form>

I have tried to update the key/value as above in the onChange method, but the console says that I cannot call .target on null. For some reason, The event.target returns null, I am not sure why. If anyone has a better solution to add the value typed to update the state, please do help.

2
  • Have you tried console.log(e, e?.target) Commented Apr 16, 2020 at 18:04
  • @ZohaibIjaz Yes, I tried. It works and it can console log but when i do that inside the setState methods it throws me the same error of cannot read value of null. Commented Apr 16, 2020 at 18:11

1 Answer 1

1

The event passed to onChange is a Synthetic Event. You can't use such an event in an asynchronous way as React will reuse the event. setState calls the updater function in an asynchronous way. If you store the event value in a constant and access that in setState, it should work.

https://reactjs.org/docs/events.html

https://reactjs.org/docs/react-component.html#setstate

onChange={(e) => {
   const value = e.target.value
   this.setState((prevState) => ({
       creatives: {
          ...prevState.creatives,
          creative1: {
            ...prevState.creatives.creative1,
            title: value,
          },
        },
      }));
      console.log(this.state.details.detail1.title);
    }}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you ! That fixed the problem, but when I console log the state, Its lagging by one last character ? What could be the reason ? I have placed my console log inside the onChange method so everytime we type it logs.
I don't see the cause for that, maybe try using e.currentTarget.value instead?

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.