I want to use the map() method on the cloned object but it keeps saying "Cannot read property 'map' of undefined" but I can use it to output the servings number ({copyRecipe.servings}). And I dont understand why console.log(copyRecipe) was shown 5 times with the first 4 empty (image below). Any helps would be appreciated. Thanks in advance!
const Parent = () =>{
//I fetch data from my custom hook
const {data: recipe, error, isLoading} = useFetch(url)
return(
<Child recipe={recipe}/>
)
}
const Child = ({recipe}) =>{
//I cloned the recipe from parent component
const [copyRecipe, setCopyRecipe] = useState({});
let duplicate = { ...copyRecipe };
useEffect(() => {
setCopyRecipe({...recipe});
}, [recipe]);
//this is to increase the number of servings when clicking the Increment component
const incrementHandle = () => {
duplicate.servings = `${parseInt(duplicate.servings) + 1}`;
setCopyRecipe(duplicate);
};
console.log(copyRecipe);
return(
//I CAN USE THE CLONED OBJECT HERE!
{copyRecipe && <p>{copyRecipe.servings}</p>}
<Increment onClick={incrementHandle}/>
//I CAN'T USE THE CLONED OBJECT HERE!!!
{copyRecipe && (
<div>
{copyRecipe.ingredients.map((item,index) => {
//do something
})}
</div>
)}
)
}
