0
const [state, setState] = useState({ city: '', country: '' });

const handleCityChange = event => {
  setState(prevState => {
    console.log(prevState);
    return { ...prevState, city: event.target.value };
  });
};

//...

<input
  type="text"
  placeholder="city"
  value={state.city}
  onChange={handleCityChange}
/>

I'm trying to destructuring prevState, which is an object, and update only the city property. On first keystroke, it's working fine without error, but as soon as I'm typing second letter, i will hit error

Uncaught TypeError: Cannot read property 'value' of null

May I know which part is the null coming from? And from chrome console I see below warning not sure if it's related

Warning: This synthetic event is reused for performance reasons. If you're seeing this, you're accessing the property target on a released/nullified synthetic event. This is set to null. If you must keep the original synthetic event around, use event.persist(). See https:...//react-event-pooling for more information.

UPDATES: If we're not using setState functionally, then it's working fine?

const handleCityChange = event => {
  setState({ ...state, city: event.target.value });
};

1 Answer 1

1

An event has to be handled synchronously in React. You can extract the value from the target before you call setState:

const handleCityChange = event => {
  const { value } = event.target;
  setState(prevState => {
    return { ...prevState, city: value };
  });
};

Another way of going about it is to persist the event, and it can be used asynchronously.

const handleCityChange = event => {
  event.persist();
  setState(prevState => {
    return { ...prevState, city: event.target.value };
  });
};
Sign up to request clarification or add additional context in comments.

3 Comments

I just found out that without using functional setState, the problem will be eliminated? May I know how are they in different, if you care to explain a lil bit more about what's going on between them?
When you give a function as argument to setState, that function will be invoked asynchronously by React. Trying to dereference event.target.value in that function will not work, since you cannot use the event asynchronously.
Sort of getting the picture now. Gonna take some time to digest it. Thanks a lot!

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.