Categories
React Answers

How to Poll an API Periodically with React?

Spread the love

Sometimes, we want to poll API periodically with React.

In this article, we’ll look at how to poll API periodically with React.

Poll an API Periodically with React

To poll API periodically with React, we can call the setInterval function to create a timer that lets us run code periodically.

For instance, we can write:

import React, { useEffect, useState } from "react";

export default function App() {
  const [answer, setAnswer] = useState();

  const getAnswer = async () => {
    const res = await fetch("https://yesno.wtf/api");
    const data = await res.json();
    setAnswer(data);
  };

  useEffect(() => {
    const timer = setInterval(getAnswer, 2000);
    return () => clearInterval(timer);
  }, []);

  return <div>{JSON.stringify(answer)}</div>;
}

We call the useState hook to create the answer state.

Then we create the getAnswer fucntion with the fetch function.

We call setAnswer with data to set the answer value.

Next, we call the useEffect hook with a callback that calls setInterval with the getAnswer function and 2000 to call getAnswer every 2000 milliseconds.

We also return a function that calls clearInterval to clear the timer when we unmount the component.

The empty array in the 2nd argument makes the useEffect callback only runs when the component mounts.

And then we render the answer as a string with JSON.stringify .

Conclusion

To poll API periodically with React, we can call the setInterval function to create a timer that lets us run code periodically.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *