How to abort/cancel/ignore previous query result if new query was sent Redux Toolkit Query

536 views Asked by At

So I have such issue, user has 3 options to choose from and when he chooses one, request is sent to backend, which updates the status and sends it back, Im also updating local state when sending the request to show the result to user instantly (something like optimistic update) everything works fine until user decides to change options too fast, and at this case if he choose option 1, then option 2 and then option 3, the UI result is instant, but when I receive backend responses the options jumps back to 2 and then to 3.

So I want to somehow abort/cancel/ignore previous request if new one was sent.

1

There are 1 answers

1
Rejjak On

As this is using javascript Fetch API, we can use the Signal options for this.

export const apiController = new AbortController();
export const apiSlice = createApi({
    reducerPath: 'api',
    baseQuery: fetchBaseQuery({
        baseUrl : API_BASE_URL
    }),
    endpoints: (builder)=> ({
        getAlbums: builder.query({
            query: (page)=> ({
                url : 'photos?_start=0&_limit=5',
                signal: apiController.signal
            })
        })
    })
})

export const {useGetAlbumsQuery} = apiSlice;

and use like this as per your need

import {useGetAlbumsQuery, apiController} from './apiSlice';

const doCancel = ()=> {
    apiController.abort();
}

For more details about the Fetch API abort controller, please refer to this documentation https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort