I have a ReactTS-App and I pass a prop via Router-Dom-Props to another component. The problem here is that I can use meal.name alone, but if I use meal.food with it or meal.food alone it doesnt work anymore.
Uncaught TypeError: meal.food is undefined
I checked TypeScript- & useEffect-errors, but I didnt find a solution yet.
And are the props loaded before the first render?
UPDATE I can print the meal.food when I use it like that location.state.meal.food
but I cannot use it from the useState after I set it - I console.log it in the useEffect.
Meal.tsx
return (
<Link className="Meal Link" to={`/MealDetails/${meal.id}`} state={{ meal: meal }}>
<div className="MealIconMealName">
<div className="MealName">{meal.name}</div>
</div>
</Link>
);
};
MealDetails.tsx
const MealDetails = () => {
const location = useLocation();
const navigate = useNavigate();
const [meal, setMeal] = useState(Object);
useEffect(() => {
if (location.state) {
if (location.state.meal) {
setMeal(location.state.meal);
console.log("useEffect" + meal);
}
}
return () => {};
}, [location]);
return (
<div className="MealDetails">
<header>
<div className="HeaderText">{meal.name}</div>
</header>
<div className="MealDetailsCalorieCounter"></div>
{meal.food.map((meal : any) => (
<Food
key={meal.id}
/>
))}
</div>
);
};
Example meal-Object out of the .json file
{
"id": 1,
"name": "Breakfast",
"food": [
{
"name": "Waffeln",
"kcal" : 505
}
],
"calories": 505
}