Blog>
Snippets

Defining a Simple API Polling createAsyncThunk

Show code example on how to create a basic API polling mechanism using createAsyncThunk, that dispatches action regularly until a certain condition is met or an error occurs.
import { createAsyncThunk } from '@reduxjs/toolkit';
import axios from 'axios';

// Define the async thunk which will be used for polling
export const pollData = createAsyncThunk(
  'data/poll',
  async (_, { dispatch, getState, rejectWithValue }) => {
    try {
      // Perform your data fetching here
      const response = await axios.get('/some/api/endpoint');
      // Optional: Check if the polling should stop based on response or state
      const shouldStop = getState().yourReducer.shouldStopPolling;
      if (shouldStop) {
        // Dispatch an action or perform logic to stop the polling
        return rejectWithValue('Polling stopped conditionally.');
      }
      // Return fetched data
      return response.data;
    } catch (error) {
      // Handle error appropriately
      return rejectWithValue(error.response.data);
    }
  }
);
This code defines a createAsyncThunk called 'pollData', which makes an async request to a specified API endpoint using axios. It also includes logic to conditionally stop polling based on a stopping condition present in the Redux state.
import { useEffect } from 'react';
import { useDispatch } from 'react-redux';
import { pollData } from './pathToYourAsyncThunks';

// React component or hook that sets up the polling
const usePollData = () => {
  const dispatch = useDispatch();
  useEffect(() => {
    const intervalId = setInterval(() => {
      dispatch(pollData());
    }, 5000); // Poll every 5 seconds

    return () => clearInterval(intervalId); // Cleanup on unmount
  }, [dispatch]);
};
This code sets up a simple polling mechanism in a React component or hook using setInterval to dispatch the 'pollData' thunk every 5 seconds. It clears the interval when the component unmounts to prevent memory leaks.