Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

109
Views
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 answers
Answer question

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 Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!