Fill an array with key-value pairs
P粉865900994
2023-09-02 16:55:11
<p>I'm trying to fill an array with objects. If I execute setState, new entries are not added, but the structure of the array is expanded. For example: initial entry (0), new entry (0->0), another entry (0->0->0). However, I would like each entry to have a consecutive number. </p>
<pre class="brush:php;toolbar:false;">const [entrys, setEntrys] = useState([{ date: "", entry: "" }]);
->Click button
setEntrys((prev) => [{ ...prev, date: clickedDay, entry: hinweis }]);</pre>
The problem you encounter is that you are using a previous state in the object you pass, for example using the spread operator "prev".
What you want to do is include the previous state in the new object saved to state, e.g. "prev" as a separate element in the array - like below.
I also provide you with a codesandbox https://codesandbox.io/s/romantic-solomon-l566yy?file=/src/App.js.