createApi là core API của RTK Query, định nghĩa toàn bộ endpoints cho một base URL.
- Cấu hình
baseQuery(thườngfetchBaseQuery({ baseUrl: '/api' })) xác định cách gọi API, có thể custom để thêm auth headers hay handle token refresh. - Mỗi endpoint là query (GET) hoặc mutation (POST/PUT/DELETE), tự động tạo hooks:
getUsers→useGetUsersQuery(),addUser→useAddUserMutation(). - Cache invalidation dùng tag system:
tagTypes: ['User'], queryprovidesTags: ['User'], mutationinvalidatesTags: ['User']— khi add user xong, danh sách users tự refetch.
Ví dụ
endpoints: (builder) => ({ getUsers: builder.query({ query: () => '/users', providesTags: ['User'] }), addUser: builder.mutation({ query: (body) => ({ url: '/users', method: 'POST', body }), invalidatesTags: ['User'] }) })createApi is the core API of RTK Query, defining all endpoints for a base URL.
- The
baseQueryconfig (typicallyfetchBaseQuery({ baseUrl: '/api' })) determines how API calls are made; it can be customized to add auth headers or handle token refresh. - Each endpoint is a query (GET) or mutation (POST/PUT/DELETE), automatically generating hooks:
getUsers→useGetUsersQuery(),addUser→useAddUserMutation(). - Cache invalidation uses a tag system:
tagTypes: ['User'], query withprovidesTags: ['User'], mutation withinvalidatesTags: ['User']— after adding a user, the user list automatically refetches.
Example
endpoints: (builder) => ({ getUsers: builder.query({ query: () => '/users', providesTags: ['User'] }), addUser: builder.mutation({ query: (body) => ({ url: '/users', method: 'POST', body }), invalidatesTags: ['User'] }) })Pitfall: only one createApi per base URL — use injectEndpoints to code-split endpoints across files.