Home > Mobile >  How to render the whole value of my array
How to render the whole value of my array

Time:11-27

Iam still a bit new to react and how it works. I'm trying to create a shopping list from a list of recipe that are objects who contain an array of ingredient but react only displays the 1st element and displays the other elements after each click

here is my code :

import { useState } from 'react';
import { MealContext } from '../../../Context/MealContext';
import GroceryListComponent from './GroceryListComponent';
const GrocerysListContainer = () => {
    const [selectedMeals,setMeals] = useContext(MealContext);
    const [groceryList, setGroceryList]= useState([]);
    const [showList,setShowList] = useState(false);
   
   
    
    const handleClick = ()=>{
        setShowList(true);
        selectedMeals.forEach(meal => {
            meal.ingredient.forEach((dish)=>{
             if(!groceryList.find(({name})=>name === dish.toLowerCase())){
                 setGroceryList([...groceryList, {name : dish.toLowerCase(), qty : 1}]);
                 console.log('add')
             }else{
                console.log('remove')
              return;
                }
            })
             
         });
        
    }
  
    

    
    return (
        <div className="groceryList">
        <button className="btn btn-submit" onClick={()=>handleClick()}>Creer liste de course</button>
        {showList && <ul>
           { groceryList.map((grocery,index)=>{
            return(
                    <GroceryListComponent
                    key={index}
                    grocery={grocery}
                />
            )
           })
           } 
        </ul>}
        </div>
    );
};


export default GrocerysListContainer;


CodePudding user response:

Most likey groceryList is not getting updated in function, so it will help to add the new elements to a array and then finally add them

Quick fix

setGroceryList(list => [...list, {name : dish.toLowerCase(), qty : 1}]);

To move towards a improved solution, the quantity of existing item also needs to be udpated

const handleClick = () => {
    // can include try catch
    setShowList(true);

    let newList = []
 
    for (const meal of selectedMeals) {
       // include check with ?. and ??
       const ingredient = meal.ingredient;
       // can add another loop here
       const dish = ingredient.find(dish => !groceryList.find(({ name }) => name === dish.toLowerCase()))
      if (!dish) {
        newList.push({ name : dish.toLowerCase(), qty : 1})
      } else {
        // depends on what you want to achieve
        // increase qty or something 
      }
    }

    setGroceryList([ ...groceryList, ...newList ])
        
}

Hope it helps you in some way

Cheers

  • Related