Reactjs useEffect not showing all datas on page (after using useCallback

Viewed 33

At first i was fixing the error "React Hook useEffect has a missing dependency:" by adding the useCallback. Then new issue comes up, the API should return 10 items but only first items show on page. Wondering which part is getting wrong and cause the data not render correctly?

Here is the code:

const InStream = () => {
  const [gallery, setGallery] = useState([]);
  const [loading, setLoading] = useState(false);
  let [color] = useState("#1E9A4B"); 

  const getAPI = useCallback(() => {
    fetch(url)
      .then((res) => res.json())
      .then((res) => {
        let keys = res.values[0];
        let newData = res.values.slice(1, res.values.length);

        let formatted = [],
          data = newData,
          cols = keys,
          l = cols.length;

        for (var i = 0; i < data.length; i++) {
          var d = data[i],
            o = {};
          for (var j = 0; j < l; j++) o[cols[j]] = d[j];
          formatted.push(o);
          setGallery(formatted);
          setLoading(true);
        }
      })
      .catch((error) => {
        console.error("Error:", error);
        setTimeout(() => {
          getAPI();
        }, 1000);
      });
  }, []);

  useEffect(() => {
    getAPI();
  }, [getAPI]);
return (// my code rendering gallery data // )
export default InStream;

1 Answers

move setGallery and setLoading out of loop

Related