If we see the code below, I have tried following this solution
The line which has inline comment // HERE: Display In Console
has return the proper value Array(29) [ {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, … ]
Why was the component not rerendered? and how to handle it so it (Line with // HERE: TSX For restaurantPhotoList
comment) is re-rendered properly? [What I got in the UI is the loading text for some seconds, and then no element after the loading text is finished (There are no photos nor <h1>There is no photos ...</h1>
element)]
Here is my component RestaurantDetail
:
const RestaurantDetail = () => {
const { id } = useParams();
const [restaurantsPhotoList, setRestaurantsPhotoList] = useState<any>([]);
const [isLoading, setIsLoading] = useState<boolean>(true);
const location = useLocation();
const restaurantName = location.state?.name;
const restaurantRating = location.state?.rating;
useEffect(() => {
if(id != undefined) {
loadRestaurantDetails(id.toString());
}
}, []);
useEffect(() => {
console.info(restaurantsPhotoList); // HERE: Display In Console
}, [restaurantsPhotoList])
const loadRestaurantDetails = (id: string) => {
setIsLoading(true);
const responseRestaurant = getDetailRestaurant(id);
responseRestaurant.then((res: any) => {
return res.data;
}).then((data: any) => {
setRestaurantsPhotoList(arrayUnique(data.restaurant.photos.concat([...restaurantsPhotoList])));
}).catch((err: any) => {
console.error(err.message);
}).finally(() => {
setIsLoading(false);
})
}
return (
<div>
<section className="flex flex-col justify-start">
<h1 className="">{restaurantName}</h1>
<div className="flex flex-row justify-start gap-2">
<Star starAmount={Math.floor(restaurantRating/2)}/>
<span className="text-sm text-[#888888]">{restaurantRating/2}</span>
</div>
<div className="min-h-screen">
{
isLoading == false ? (
// HERE: TSX For restaurantPhotoList
restaurantsPhotoList.length != 0 ? (
restaurantsPhotoList.map((elmt: any, idx: any) => {
// <img key={idx} src={elmt.src} alt={restaurantName} className="w-52 h-52 rounded-md" draggable={false}/>
<div>
<p key={idx}>{elmt.src}</p>
</div>
})
) : (
<div className='flex flex-row justify-center w-screen'>
<h1>There is no photo posted by users</h1>
</div>
)
) : (
<div className='flex flex-row justify-center w-screen'>
<h1>Loading...</h1>
</div>
)
}
</div>
</section>
</div>
)
}