I am new to react and trying to understand the useState hook. What I am trying to do is, I have a input type text field and a button. On click of button, I am trying to push the entered value to an array. But currently on doing so, its adding the value to the array but clearing it back and making the array empty. Could any one please tell me why its happening and how to fix it. Below is what I have done.
import React, { useState } from "react";
const HookCounter5 = () => {
const [item, setItem] = useState([]);
const [name, setName] = useState({ firstName: "" });
const handlePushNameToArray = () => {
setItem(...item, name.firstName);
};
return (
<div>
<form>
<input
type="text"
value={name.firstName}
onChange={(e) => setName({ ...name, firstName: e.target.value })}
></input>
<button onClick={handlePushNameToArray}>Push to array</button>
<div>{JSON.stringify(item)}</div>
</form>
</div>
);
};
export default HookCounter5;
2
Answers
You are not using the spread operator correctly. While updating state, use array square brackets.
This method wouldn’t work if component is not re rendered after updating name state(this happens because react bathces all the state changes and then updates).
In that case, you can use the other form of useState syntax like below:
Use the same for name also.
Actually, it was getting pushed to to the array except the state was set to its inital value because the whole page refreshed.
e.preventDefault()
is not present.Solutions (please do either one only)
handlePushNameToArray
as an onSubmit on the form tag and remove the onClick callback from the buttonHere’s the working code
Here’s how I would do it