Search code examples
reduxrtk-query

how to split RTK Query files with endpoint injection


I'm using RTK Query successfully in my project, but I have 8 tags/data sets and each of those needs a getOne, getAll, add, update, delete, undelete query/mutation and some need more. It's getting hard to manage so I'm trying to use injectEndpoints to split the queries up by tag using the tutorial at https://redux.js.org/tutorials/essentials/part-8-rtk-query-advanced#injecting-endpoints.

Unfortunately, when using their code structure, I get an error Uncaught ReferenceError: builder is not defined. Am I missing something?

import { apiSlice } from "./apiSlice";

export const accountsSlice = apiSlice.injectEndpoints({
    endpoints: builder ({
        getAccounts: build.query({
            query: () => ({
                url: '/api/accounts',
                method: 'get'
            }),
            providesTags: (result, error, arg) => [{ type: 'Account', id: arg }]
        }),
        getAccount: build.query({
            query: accountId => ({
                url: `/api/accounts/${accountId}`,
                method: 'get',
            }),
            providesTags: (result, error, arg) => [{ type: 'Account', id: arg }]
        }),
        addAccount: build.mutation({
            query: (account) => {
                console.log('account data:', account);
                return {
                    url: `/api/accounts/store`,
                    method: 'post',
                    data: account
                }
            },
            invalidatesTags: (result, error, arg) => [{ type: 'Account'}]
        }),
        updateAccount: build.mutation({
            query: (account) => {
                console.log('account data:', account);
                return {
                    url: `/api/accounts/${account.acc_id}/update`,
                    method: 'patch',
                    data: account
                }
            },
            invalidatesTags: (result, error, arg) => [{ type: 'Account', id: arg.id}]
        }),
    })
})

Solution

  • It's a function definition with an argument called builder, not a call to the function builder:

    Instead of builder({ /* ... */ }) (as in your code),

    it should be

    builder => ({ /* ... */ })
    

    which is short for

    (builder) => ({ /* ... */ })
    

    or

    function anonymous(builder) {
      return {
        /* ... */ 
      }
    }