TL;DR
You need to pass to setResults a new array, perform the spread on the "result" parameter and then add the input value after that:
setResult([...result, input]);
In more detail:
So let me go over the code to explain the problem.
export default function App() {
const [input, setInput] = useState("");
const [result, setResult] = useState([]);
const handleSubmit = (e) => {
e.preventDefault();
// Spread operator??
setResult(...input, input);
console.log(input);
};
return (
<div className="App">
<form>
<input type="text" onChange={(e) => setInput(e.target.value)}></input>
<button type="submit" onClick={handleSubmit}>
submit
</button>
</form>
<h2>{result}</h2>
</div>
);
}
From what I understand you were trying to create an input (whose value is stored int he "input" state) that submits the data you type in it into an array (the "result" array).
You defined the behaviour of the input correctly:
<input type="text" onChange={(e) => setInput(e.target.value)}></input>
Whenever the user types something into the input, the value (a string) is stored into the input state via set state, which, as a useState hook, takes 1 argument and updates the state to hold it.
Now note that result is also a useState hook, meaning that setResult behaves exactly the same - it expects 1 argument and stores that value into the state.
Here are the problems in your code:
- You spread the wrong value - ...input will spread the string "input"'s characters as separate values (i.e.
[..."test"] will give you ```["t", "e", "s", "t"].
- Rather than spreading values into a new array, you spread the values as arguments to setResults.
As a result, every time you submitted the form, you passed the first letter of your input to setResults, changing it from an array to a string holding the first character of the input:
