Isaac
Isaac

Reputation: 12874

Simple setState on object using hooks

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 });
};

Upvotes: 0

Views: 179

Answers (1)

Tholle
Tholle

Reputation: 112807

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 };
  });
};

Upvotes: 1

Related Questions