Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

119
Vistas
How to add a new json object to array which elements will be rendered as components on a page?

I want to change a state of an array which will have values derived from data.js file as a starting point. Changing a state means running function setAllThingsArray and adding new element which will be set using a function setThingsArray based on previous state (thingsArray). Do I need to map allThingsArray to get updated array with added elements and to list them ?

import React from "react";
import data from "../data";
import Stamp from "../components/Stamp";

export default function AddItem(props) {
  
  const [thingsArray, setThingsArray] = React.useState({
    key: 9,
    img: "../images/stamp1.jpg",
    name: "Stamp 5",
    description: "AAAA",
    rating: 78.0,
  });

  function addItem() {
    setAllThingsArray((prevAllThingsArray) => ({
      arr: [
        ...prevAllThingsArray.arr,
        setThingsArray((prevThingsArray) => ({
          ...prevThingsArray,
          key: prevThingsArray.key + 1,
          img: "../images/stamp1.jpg",
          name: "Stamp 5",
          description: "AAAA",
          rating: 78.0,
        })),
      ],
    }));
  }

  const [allThingsArray, setAllThingsArray] = React.useState(data);

  const allThingsElements = allThingsArray.map((st) => {
    return <Stamp key={st.key} st={st} />;
  });

  return (
    <>
      <div className="form">
        <input type="text" placeholder="Image" className="form--input" />
        <input type="text" placeholder="Stamp title" className="form--input" />
        <input type="text" placeholder="Description" className="form--input" />
        <input type="text" placeholder="Rating" className="form--input" />
        {/* <button className="form--button" onClick={addStampToJson(json_stamp)}>
          Add Stamp
        </button> */}
        <button className="form--button" onClick={addItem}>
          Add Stamp
        </button>
      </div>
      <section className="stamps-list">{allThingsElements}</section>
    </>
  );
}


Is it correct to place setThingsArray function inside setAllThingsArray function?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

state setters (setAllThingsArray and setThingsArray) are asynchronous, so you cannot use a state update within another state update. setThingsArray itself is also a function (not a state value), so you cannot set it directly into setAllThingsArray either.

I'd propose that you should add another variable to keep an updated object (not an updated state), and then update states separately with the updated object.

function addItem() {
    //add an updated object
    const updatedThingsArray = {
        ...thingsArray, //this is an actual previous state
        key: prevThingsArray.key + 1,
        img: "../images/stamp1.jpg",
        name: "Stamp 5",
        description: "AAAA",
        rating: 78.0,
    }
    setAllThingsArray((prevAllThingsArray) => ([
        ...prevAllThingsArray,
        updatedThingsArray, //it's become a new object with your updated data
      ]));

    setThingsArray(updatedThingsArray) //update it back to the `thingsArray` as the new state
  }
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda