Home  >  Q&A  >  body text

Fill an array with key-value pairs

<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粉865900994P粉865900994385 days ago456

reply all(1)I'll reply

  • P粉475315142

    P粉4753151422023-09-03 10:59:11

    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;

    reply
    0
  • Cancelreply