avatarJohn Au-Yeung

Summary

The article explains how to periodically poll an API in a React application using the setInterval function to fetch data at regular intervals.

Abstract

The article titled "How to Poll an API Periodically with React?" provides a technical guide on implementing periodic API polling within a React application. It introduces the concept of polling, which is the practice of repeatedly executing a function to check for updates or new data from an API. The author demonstrates this by creating a getAnswer function that fetches data from an example API endpoint every 2000 milliseconds using setInterval. The article also emphasizes the importance of cleaning up the interval timer when the component unmounts to prevent memory leaks, achieved by returning a cleanup function from the useEffect hook. The article concludes by reiterating the use of setInterval for periodic API polling and encourages community engagement by inviting readers to clap, follow, and contribute to the "In Plain English" platform.

Opinions

  • The author suggests that polling an API periodically is a useful technique in React development when updates are expected at regular intervals.
  • It is implied that using the useEffect hook with an empty dependency array is the correct approach to ensure the interval is set up only once when the component mounts.
  • The article promotes best practices by showing how to clear the interval timer upon component unmount, which is crucial for avoiding memory leaks and unwanted behavior.
  • The inclusion of a real-world API endpoint (https://yesno.wtf/api) in the example code provides a practical illustration of the polling concept.
  • The author encourages reader interaction and community building by inviting readers to engage with the content and consider writing for the platform, indicating a belief in the value of shared knowledge and collaborative learning.

How to Poll an API Periodically with React?

Photo by Jen Theodore on Unsplash

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.

PlainEnglish.io 🚀

Thank you for being a part of the In Plain English community! Before you go:

Programming
Web Development
Technology
Software Development
JavaScript
Recommended from ReadMedium
avatarAnahit Vardevanyan
Design Patterns in React

Introduction

4 min read