I'm trying to redirect mealContainer to Meals for showing details of that data. By the way, I'm using mealDB for the API. But the problem is when I click meal categories div for showing details, sometimes it becomes null and sometimes it shows the data. I don't know why it's happened. So I'm trying to show a warning when it will be null by using the ternary operator. How can I do that?
import React, { useState } from "react";
import Meals from "../Meals/Meals";
import "./MealCategory.css";
const MealCategory = ({ mealCategory }) => {
const { strCategory, strCategoryThumb } = mealCategory;
const [mealsContainer, setMealsContainer] = useState([]);
const handleOnClick = (e) => {
e.preventDefault();
const categoryName = e.target.innerText;
const categoryUrl = `https://www.themealdb.com/api/json/v1/1/filter.php?c=${categoryName}`;
fetch(categoryUrl)
.then((res) => res.json())
.then((data) => setMealsContainer(data.meals));
// .then(data => console.log(data))
};
return (
<div>
<div onClick={handleOnClick} className="col py-3 text-center">
<div className="card d-flex flex-row align-items-center">
<div className="img">
<img src={strCategoryThumb} className="card-img-top" alt="..." />
</div>
<div className="card-body">
<h1 className="card-title fs-2">{strCategory}</h1>
</div>
</div>
</div>
{mealsContainer.map((meals) => (
<Meals meals={meals} />
))}
</div>
);
};
export default MealCategory;
As you are saying sometimes you get null, so even if you use ternary operator inside map, then also you will get error as you can't run map on an array which evaluates to null.
Yes, if your concern is how to use ternary operator inside map, then :
{mealsContainer ?
mealsContainer.map(meals => <Meals meals={meals} />) : <p>Error loading data!</p>
}