Search code examples
javascriptreactjsreduxredux-toolkitrtk-query

How to make a RTK Query GET request inside the reducer of a Redux Toolkit slice?


I am having some difficulty understanding how to handle side effects such as HTTP requests when I am using RTK Query. From what I understood by reading the documentation, if I use RTK Query I wouldn't have to use Redux Thunk which would simplify a lot of stuff.

Currently I have a simple postsSlice which has a getPosts reducer. I would like to make a GET requests in that reducer in order to get all the posts and then set the state to the response. I understand that if I weren't using RTK Query I would need to create a Redux Thunk action here. I can easily make the request in a React component using the useGetPostsQuery hook supplied by RTK Query, but how am I supposed to make that GET request from inside Redux considering it is not a React component or hook?

export const postsSlice = createSlice({
    name: 'posts',
    initialState,
    reducers: {
        getPosts: (state) => {
            // I want to make a GET request to /getPosts here
        },
    },
});

And I have the following apiSlice:

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';

export const apiSlice = createApi({
    reducerPath: 'api',
    baseQuery: fetchBaseQuery({ baseUrl }),
    endpoints: (builder) => ({
        getPosts: builder.query({
            query: () => '/posts',
        }),
    }),
});

export const { useGetPostsQuery } = apiSlice;

Solution

  • First: you are never allowed to put any side effect into a Redux reducer. A Redux reducer needs to be pure (side-effect-free) and synchronous. This wouldn't be allowed with a thunk either.

    But you are also missing out on a few more points: RTK Query already creates a reducer for you and also manages that state for you. You don't need to save the result of RTK Query into a slice, because RTK Query already did that - and usually you should not duplicate data within your store.

    I would highly recommend you go over the RTK-Query-specific chapters of the Redux tutorial, starting at chapter 7