Home > Software design >  how to call to api once a hour with react
how to call to api once a hour with react

Time:01-03

i would like to know how can i get the api on first time reload the page and then call to api again once a hour to update my UI because that api update once a hour by default

here is my code

const [news, setNews] = useState([])

useEffect(() => {
    setInterval(() => {
        (async () => {
            tryÏ {
                const res = await fetch(`https://newsapi.org/v2/top-headlines?country=""""&apiKey=""""""""`)
                const data = await res.json()
                setNews(data)
                console.log("yes")
            } catch (error) {
                console.log(error)
            }
        })()
    }, 36000000);
}, [])

with that code i can't get result on first time page reload, only after a hour...

CodePudding user response:

Move your API call to separate function. Call it on page load and on timeout:

let callApi = async () => {
        try {
            const res = await fetch(url)
            const data = await res.json()
            setNews(data)
            } catch (error) {
            console.log(error)
        }
    };

useEffect(() => {
    callApi();

    setInterval(callApi, 1000 * 60 * 60)
});

CodePudding user response:

You can create another function and call from interval and outside both.

const [news, setNews] = useState([]);

useEffect(() => {
  const fetchData = async () => {
    try {
      const res = await fetch(
        `https://newsapi.org/v2/top-headlines?country=""""&apiKey=""""""""`
      );
      const data = await res.json();
      setNews(data);
      console.log("yes");
    } catch (error) {
      console.log(error);
    }
  };
  fetchData();
  const interval = setInterval(() => {
    fetchData();
  }, 36000000);

  return () => clearInterval(interval);
}, []);
  • Related