user17302724
user17302724

Reputation:

how to call to api once a hour with react

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...

Upvotes: 0

Views: 1764

Answers (3)

Alexander Kosykh
Alexander Kosykh

Reputation: 371

You can try this code:

const [news, setNews] = useState([]);
  const [timer, setTimer] = useState(null);

  const APIResponse = async (url) => {
    try {
      const response = await fetch(url);
      const data = await response.json();
      setNews(data);
    } catch (e) {
      console.error(e);
    }
  };

  useEffect(() => {
    APIResponse("https://newsapi.org/v2/top-headlines?country=""""&apiKey=""""""""");
    setTimer(
      setInterval(async () => {
        APIResponse("https://newsapi.org/v2/top-headlines?country=""""&apiKey=""""""""");
      }, 5000)
    );
    return () => clearInterval(timer);
  }, []);

Upvotes: 0

Rahul Sharma
Rahul Sharma

Reputation: 10071

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);
}, []);

Upvotes: 1

Justinas
Justinas

Reputation: 43451

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)
});

Upvotes: 1

Related Questions