Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

110
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

0

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda