thecluff
thecluff

Reputation: 15

Auto refresh JSON data on an set interval in React Native using React Hooks

I'm working on a React Native app for a radio station which displays song & artist info from a JSON url. How can I get the info to update/fetch every minute or so? I've tried a few variations of using setInterval, but can't seem to get it to work in my functional component. I'm guessing it's because I'm trying to use setInterval with an async function..? Thanks in advance!

  const [track, setTrack] = useState({});

  async function fetchData() {
    const res = await fetch(" my API url ");
    res
      .json()
      .then(res => setTrack(res.data[0].track.title))
      .catch(err => setErrors(err));
  }
  useEffect(() => {
      fetchData();
  });
<Text>{track}</Text>

Upvotes: 0

Views: 2808

Answers (1)

giankotarola
giankotarola

Reputation: 775

You can use setTimeout to request every N period of time after first component mount, like:

import React from 'react';

const Component = () => {
    const [track, setTrack] = React.useState('');

    React.useEffect(() => {
        let repeat;

        async function fetchData() {
            try {
                const res = await fetch(" my API url ");
                const json = await res.json();

                setTrack(json.data[0].track.title);

                repeat = setTimeout(fetchData, 60000); // request again after a minute
            } catch (error) {
                console.error(error.message)
            }
        }

        fetchData();

        return () => {
            if (repeat) {
                clearTimeout(repeat);
            }
        }
    }, []);

    return (
        <Text>{track}</Text>
    );
};

Upvotes: 1

Related Questions