Home > Mobile >  Addinng items to an Accordion in React
Addinng items to an Accordion in React

Time:04-09

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?

CodePudding user response:

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.

CodePudding user response:

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

  • Related