Fill an array with key-value pairs
P粉865900994
P粉865900994 2023-09-02 16:55:11
0
1
509
<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>
P粉865900994
P粉865900994

reply all(1)
P粉475315142

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.

import "./styles.css";
import React, { useState } from "react";

const App = () => {
  const [entries, setEntries] = useState([
    {
      date: "",
      text: ""
    }
  ]);

  const handleClick = () => {
    setEntries((prevEntry) => {
      return [...prevEntry, { date: "date", text: "test" }];
    });
  };

  return (
    <div>
      <button onClick={handleClick}>Click me!</button>
    </div>
  );
};

export default App;
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template