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

112
Vistas
Addinng items to an Accordion in React

I'm making a diet project I have two inputs with meal name and hour, (eg: Breakfast 8am). Then i have a button that renders an Accordion with those values and another button. The Accordion is a Material UI component, so to render a new Accordion everytime, i passed the Accordion as an object property, then i add that obj to an empty array and render the array with the map method.

The button created with each accordion does this:

const [foodList, setFoodList] = useState([]);

function addFood() {
    const food = {
      id: Math.random(),
      name: input,
      amount: amount,
    };

    setFoodList([...foodList, food]);
  }

And the accordion content is this:

<Typography>
          {foodList.map((item) => {
            return (
              <div key={item.id}>
                <h1>{item.name}</h1>
                <h2>{item.amount}</h2>
              </div>
            );
          })}
        </Typography>

When i render the accordion for the first time, it does not add the food object to the foodList. The second time, it adds one time and then no more, the third time adds twice and then no more.

Why is this happening?

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

0

You'll have to use the useEffect hook

const [foodList, setFoodList] = useState([]);

function addFood() {
    const food = {
      id: Math.random(),
      name: input,
      amount: amount,
    };
    // Here please consider using the prevState
    setFoodList(prevState => ([...prevState, food]));
  }
useEffect(() => {
    // Here your code to be executed when dependency is updated
}, [dependency])

The "error" you are facing is typically caused by the fact that you don't use the useEffect hook.

about 4 years ago · Juan Pablo Isaza Denunciar

0

Try to use useEffect with dependency addFood. So every time you run addFood function component renders.

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