reactjstypescriptreact-hooksfetch-apisetinterval

Fetch and setInterval react hooks problem


I recently used hooks with React to fetch data from server but i'm facing a problem with hooks. The code seems correct but it look like the useEffect isn't called at first time but 3 seconds after with the setInterval. I have blank table for 3 seconds before it appear. I want to directly show the data and call it 3 seconds later.

What is the correct way to use it?

const [datas, setDatas] = useState([] as any);

useEffect(() => {
  const id = setInterval(() => {
    const fetchData = async () => {
      try {
        const res = await fetch(URL);
        const json = await res.json();
        setDatas(jsonData(json));
      } catch (error) {
        console.log(error);
      }
    };
    fetchData();
  }, TIME)

  return () => clearInterval(id);
}, [])

Solution

  • You need to invoke fetchData once initially outside the interval. Define fetchData outside the interval.

    useEffect(() => {
      // (1) define within effect callback scope
      const fetchData = async () => {
        try {
          const res = await fetch(URL);
          const json = await res.json();
          setDatas(jsonData(json));
        } catch (error) {
          console.log(error);
        }
      };
        
      const id = setInterval(() => {
        fetchData(); // <-- (3) invoke in interval callback
      }, TIME);
    
      fetchData(); // <-- (2) invoke on mount
    
      return () => clearInterval(id);
    }, [])