🪴 notes

Search

Search IconIcon to open search

rtk-q createApi

Published May 5, 2023 Last updated May 5, 2023 Edit Source

docs

One of rtk query’s api that help with keeping code that interact with an backend api with a common baseUrl.

source

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
export const authApi = createApi({
    reducerPath: 'authApi',
    baseQuery: fetchBaseQuery({
        baseUrl: `${BASE_URL}/api/auth/`,
        credentials: 'include'
    }),
    endpoints: (builder) => ({
        signUpUser: builder.mutation<ResponseType, QueryParamType>({
            query: (data) => ({
                url: 'register',
                method: 'POST',
                body: data
            }),
        }),
        logoutUser: builder.query<ResponseType, QueryParamType>({
            query: () => `logout`,
        }),
        refresh: builder.query<ResponseType, QueryParamType>({
            query: () => ({
                url: 'refresh',
                method: 'GET',
            }),
        }),
        resetPassword: builder.mutation<ResponseType, QueryParamType>({
            query: ({ resetToken, password }) => ({
                url: `/resetpassword/${resetToken}`,
                method: 'PATCH',
                body: {
                    password
                }
            }),
        }),
    }),
})

The endpoints property is where to define interactions with the backend api. queries are GET requests and doesn’t take a body attribute, unlike mutation which corresponds to writes to possible writes to the database like POST and PATCH.

1
2
3
4
5
export const {
    useSignUpUserMutation,
    useLogoutUserQuery,
    useResetPasswordMutation
} = authApi;

createApi generates hooks for the endpoints making it easier to get the state and data from the responses from within react components. Sometimes, it’s necessary to call these endpoints outside react components such is the case [dev_notes/react forms|here]