Search code examples
javascriptreduxredux-toolkitpollingrtk-query

Access the history of responses of a useQuery hook that uses polling


In my app, I need to display the historic state of a server, similar to following image:

enter image description here

The endpoint I use is a normal GET fetch. So I need polling to retrieve the data periodically:

  const { data, isFetching, error } = useGetServerStateDataQuery(id, {
    pollingInterval: 3000,
  })
  console.log(data) // data only contains LAST response :(

The problem is that data only contains last response, and I need the historic of all responses to be able to draw the progress. Is there any built-in redux-toolkit solution to access the history of responses?


Solution

  • There are multiple approach:

    Using extra reducers

    You can link a timestamp in the meta

    Then plug the result of your endpoint into an extra reducer to keep track of this history of results

    const weatherSlice = createSlice({
      name: 'weather',
      initialState,
      reducers: {
         history: {}
      },
      extraReducers: (builder) => {
        builder.addCase(api.endpoints.getServerStateDataQuery.fullfilled, (state, action) => {
          state.history[action.meta.timestamp] = action.payload
        })
      },
    })
    

    Using entity adapters

    You can store each temperature info into an entity object with an entity adapter

    const weatherInfoAdapter = createEntityAdapter<Book>({
      selectId: (info) => info.id,
      sortComparer: (a, b) => a.timestamp.localeCompare(b.timestamp),
    })
    
    const weatherSlice = createSlice({
      name: 'weather',
      initialState: weatherInfoAdapter.getInitialState(),
      reducers: {
         history: {}
      },
      extraReducers: (builder) => {
         builder.addCase(api.endpoints.getServerStateDataQuery.fullfilled, (state, action) => {
          weatherInfoAdapter.addOne(state, action.payload)
        })
      },
    })