Skip to content
Middle+7 views

What RTK Query tools are used for sending requests and how would you send requests after connecting the library?

Practice

AI answer

Requests are described in createApi as endpoints: builder.query is used to fetch data, while builder.mutation is used to modify data. RTK Query usually generates React hooks for each endpoint, such as useGetUsersQuery and useUpdateUserMutation. For a request that needs to be triggered manually, there are lazy hooks, such as useLazyGetUsersQuery.

const api = createApi({
  baseQuery: fetchBaseQuery({ baseUrl: '/api' }),
  endpoints: (builder) => ({
    getUsers: builder.query<User[], void>({ query: () => 'users' }),
    updateUser: builder.mutation<User, UpdateUser>({
      query: ({ id, ...body }) => ({ url: `users/${id}`, method: 'PUT', body }),
    }),
  }),
});

export const { useGetUsersQuery, useUpdateUserMutation } = api;

In a component, useGetUsersQuery() triggers the request and provides the data and loading/error state; useUpdateUserMutation() returns a trigger function that you call in response to a user action. You can also send requests manually with dispatch(api.endpoints.getUsers.initiate()), but hooks are generally more convenient in React components.