I'm new to React hooks, trying to set a state, while also using prevState:
const [inputs, setInputs] = useState("");
const changeHandler = (e) => {
setInputs((prevState) => e.target.value);
};
return (
<input
onChange={changeHandler}
type="text"
id="title"
/>
The prevState isn't necessary but its presence is what causing the error after typing more than one character in the input field. Does anyone know why?
CodePudding user response:
You're accessing the event asynchronously, but as the error says, the event object is reused.
Don't access the event asynchronously. Instead, extract the value you need synchronously.
const changeHandler = (e) => {
const { value } = e.target;
setInputs(prevState => value);
};
Using the callback of setInputs
doesn't do anything here though. You'd need to use a callback only if you previously updated the state before changeHandler
was called, and before a re-render. You'd also need to use a callback only if you need to factor in the previous state into the new state. For example, if you did something like
onChange={(e) => { doSomethingThatChangesState(e); changeHandler(e); }}
and if the state was an object with multiple values:
const changeHandler = (e) => {
const { value } = e.target;
// update the `value` property in state:
setInputs(prevState => ({...prevState, value }));
};
CodePudding user response:
It looks like you are using a slightly older version of React, pre-17, that uses an event pool. Event objects are nullified and returned to the event pool before the enqueued state update is processed asynchronously.
It's not an issue with the non-functional state update because you access the event object synchronously, passing the current value to the state updater.
If you need the event value for a functional state update then save a copy of it in callback scope.
const changeHandler = (e) => {
const { value } = e.target;
setInputs((prevState) => {
// reference value here safely
});
};