React JS map cards images

Viewed 68

While im getting imgs list from API by custom hook show loader component, then map list. Problem - card item images shows not the same time. enter image description here

Custom hook :

import { useState, useEffect } from "react";

export default function useFetch(typeTabByPopular, tabListType) {
  const [list, setList] = useState("");
  const [page, setPage] = useState("1");
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    setLoading(true);
    fetch(
      `https://api.themoviedb.org/3/trending/${tabListType}/
      ${typeTabByPopular}?api_key=${process.env.REACT_APP_API_KEY}&&page=${page}`,
    )
      .then((response) => response.json())
      .then((data) => {
        setList(data);
        setLoading(false);
      });
  }, [tabListType, typeTabByPopular, page]);
  return { list, setPage, loading };
}
1 Answers

All image elements have an onLoad event you can use to benefit this aim.

Since you have a list of images, then you know how many images should be on each page. Put a counter of loadedImages and on the onLoad of each image using setLoadedImages to raise it by 1.

Until the counter is equal to the number of images on the page render a loader and when it matches the number of images render the images.

Related