7 views
What RTK Query tools are used for sending requests and how would you send requests after connecting the library?
Asked at
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.
Also asked at Глобус
- Tell us about yourself, your experience, and your recent projects.
- Tell me more about your experience with Feature-Sliced Design (FSD): which layers did you implement, was it convenient or not, and what problems arose?
- Did you have experience with microfrontends? Can you roughly describe how it was organized?
- Do you follow news about React, in particular changes starting from React 19? How do React 18 and React 19 differ in terms of concurrent rendering?
- If you do not memoize the values and callbacks passed through props using useMemo and useCallback, will React.memo be useful?