0

I'm learning how to render a list in React so I'm playing around with this example. When I first click on one button, the item is not rendered immediately in the the . I check with console.log(clickedItem) then the first item is an empty string. Can aynone help understand this behaviour in my code. Thanks!

import React, { useState } from "react";
const Grocceries = () => {
  //List of food items
  const foodList = [
    "coffee",
    "potatoes",
    "drinks",
    "spices",
    "bananas",
    "oranges",
    "oatmeal",
    "bread",
    "flowers",
  ];

  //Create a state for "grocceries" useState has initial value of an empty array
  const [grocceries, setGrocceries] = useState([]);
  //Create a state for clicked item, initial value is an empty string
  const [clickedItem, setClickedItem] = useState("");

  const addFoodItem = (e) => {
    setClickedItem(e.target.value);
    // console.log(clickedItem);
    setGrocceries((grocceries) => [...grocceries, clickedItem]);
  };

  const rendered = foodList.map((foodItem, index) => (
    <li key={index}>
      <button
        className="waves-effect waves-light btn col s4"
        value={foodItem}
        onClick={addFoodItem}
      >
        {foodItem}
      </button>
    </li>
  ));

  const renderedGrocceries = grocceries.map((item, key) => (
    <li key={key + 1} value={item}>
      {item}
    </li>
  ));

  return (
    <div className="App container">
      <div className="row">
        <div className="col s3" />
        <div className="card col s6">
          <span class="card-title">My Shopping list</span>

          <p>Remember to grab...</p>

          <ul className="shopping-list">{renderedGrocceries}</ul>
          <ul className="collection">{rendered}</ul>
        </div>
      </div>
    </div>
  );
};
export default Grocceries;```


 
  • Are you looking for this? https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately – ace1234 Aug 10 '21 at 19:26
  • React state updates are enqueued and asynchronously processed. The state value will be the value from the current render cycle and not what you enqueue it to be for the next render cycle. Typically you would use an `useEffect` hook to listen for state updates, but in this case I don't see the point of the `clickedItem` state, just push the new value into the array, i.e. `setGroceries((groceries) => [...groceries, e.target.value]);`. – Drew Reese Aug 10 '21 at 19:32

0 Answers0