Andres Mejias
Andres Mejias

Reputation: 74

React fetch data every 500 ms or less

I'm trying to check my data every time they update by seeing other forums try to use:

  async function fetchData() {
    try {
      const url = `${baseUrl}/api/turn`;
      const res = await axios.get(url);
      setTurns(res.data);
    } catch (error) {
      console.log(error);
    }
  }

  React.useEffect(() => {
      const timer = setInterval(() => {
        fetchData();
      }, 500);
      return () => {
        clearInterval(timer);
      };
  }, []);

It works but it throws me this error

enter image description here

And it makes sense ... but I tried to find more information to solve it but I couldn't solve it.

I need some help with this.

Thanks in advance.

Upvotes: 0

Views: 761

Answers (2)

user2740650
user2740650

Reputation: 1753

I take it this error is probably sporadic? I also assume setTurns is a useState setter.

I think what could happen is that when the component is unmounted, you correctly cancel any pending timer, but you're not actually cancelling any async request. I'd suggest restructuring so that a new request is only emitted 500ms after the old one completes, because right now you could issue multiple requests if the network is slow.

Upvotes: 1

JLD
JLD

Reputation: 570

You're getting that error because you're trying to setState after component is unmounted.

  React.useEffect(() => {
      let isMounted = true;
      const timer = setInterval(() => {
        const fetchData = async () => {
         try {
          const url = `${baseUrl}/api/turn`;
          const res = await axios.get(url);
          if (isMounted) {
          setTurns(res.data);}
         } catch (error) {
          console.log(error);
         }
        }
        fetchData();
      }, 500);
      return () => {
        isMounted = false
        clearInterval(timer);
      };
  }, []);

Upvotes: 1

Related Questions