Search code examples
reactjsuse-effect

useEffect with time interval runs twice each time


Hello I have a simple application where I fetch data every 3 seconds by using useEffect with time interval. Everything works as needed buy by logging in the console I see that my useEffect works twice, it calls fetchData function twice almost at the same time. I think I am missing something in my code. Thank you for your help!

       useEffect(() => {
        const interval = setInterval(() => {
          fetchChatData();
        }, 3000);
        return () => clearInterval(interval);
      });

  const fetchChatData = () => {
    setError(null);

    async function fetchData() {
      const request = await axios.get(
        "https://api.jsonbin.io/v3/b/60e6d8a81f8e4a7f2a",
        {
          headers: {
            "Content-Type": "application/json",
            "X-Master-Key":
              "$2b$10$OSaM64SeFaeWQMwrro08kuypgEG7Q",
          },
        }
      );
      const responseData = await request.data;
      chatCtx.setChatData(responseData.record);
    }

    fetchData();
    fetchData().catch((error) => {
      setError(error.response.data.message);
    });
  };

Solution

  • You are calling fetchData function twice out of useEffect that causes the second API call.

    Remove

    fetchData();
    

    before

    fetchData().catch((error) => {
          setError(error.response.data.message);
        });