Blog>
Snippets

Using React Hooks for Polling with createAsyncThunk

Illustrate the use of React's useEffect and useDispatch hooks to trigger and clean up API polling behavior created with createAsyncThunk.
import React, { useEffect } from 'react';
import { useDispatch } from 'react-redux';
import { createAsyncThunk } from '@reduxjs/toolkit';

// Define the async operation using createAsyncThunk
const fetchData = createAsyncThunk('data/fetch', async (_, { rejectWithValue }) => {
  try {
    const response = await fetch('https://api.example.com/data');
    const data = await response.json();
    return data;
  } catch (error) {
    return rejectWithValue(error.message);
  }
});

const MyComponent = () => {
  const dispatch = useDispatch();

  useEffect(() => {
    // Define the interval ID here so it can be accessed later to clear the interval
    let intervalId;

    const pollData = async () => {
      await dispatch(fetchData());
    };

    // Start polling
    intervalId = setInterval(pollData, 3000);

    // Cleanup function to stop polling when component unmounts
    return () => clearInterval(intervalId);
  }, [dispatch]); // Dependency array to ensure effect runs once

  return (
    <div>
      {/* Render your component UI here */}
    </div>
  );
};

export default MyComponent;
This code defines a React functional component that uses the useEffect hook to start polling data from an API every 3 seconds when the component is mounted. The polling is done with an asyncThunk created by Redux Toolkit, ensuring compatibility with Redux state management. The cleanup function within useEffect makes sure to clear the interval when the component is unmounted to prevent memory leaks.