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;```