반응형
// client
export const apiSlice = createApi({
reducerPath: 'api',
baseQuery: fetchBaseQuery({
baseUrl: 'http://localhost:4000/api', // API 기본 경로
prepareHeaders: (headers, { getState }) => {
// 예: 인증 토큰 추가
const token = getCookie('access_token');
if (token) {
headers.set('Authorization', `Bearer ${token}`);
}
// 다른 커스텀 헤더 추가
headers.set('Content-Type', 'application/json');
return headers;
},
}),
// posts
import { apiSlice } from './client';
const extendedApi = apiSlice.injectEndpoints({
endpoints: (builder) => ({
getPosts: builder.query({
query: () => '/posts',
providesTags: ['Post'],
}),
getPostById: builder.query({
query: (id) => `/posts/${id}`,
providesTags: (result, error, id) => [{ type: 'Post', id }],
}),
createPost: builder.mutation({
query: (newPost) => ({
url: '/posts',
method: 'POST',
body: newPost,
}),
invalidatesTags: ['Post'],
}),
updatePost: builder.mutation({
query: ({ id, ...updatedPost }) => ({
url: `/posts/${id}`,
method: 'PUT',
body: updatedPost,
}),
invalidatesTags: (result, error, { id }) => [{ type: 'Post', id }],
}),
deletePost: builder.mutation({
query: (id) => ({
url: `/posts/${id}`,
method: 'DELETE',
}),
invalidatesTags: (result, error, id) => [{ type: 'Post', id }],
}),
}),
overrideExisting: false,
});
export const {
useGetPostsQuery,
useGetPostByIdQuery,
useCreatePostMutation,
useUpdatePostMutation,
useDeletePostMutation,
} = extendedApi;
기본 주소를 /api로 해두고 모듈마다 유지보수를 위해 코드를 쪼개는 작업을 위해 적용중이다.
/api/auth
/api/posts
로 관리하려고 쪼개는 작업중이었다.
// 호출 샘플 예시
const [register, { isLoading: registerLoading, error: registerError }] =
usePostRegisterMutation();
그런데, 아무리해도 방법이 없어서 찾고 다녔는데
공식문서에 해당 내용이 적혀있더라
메소드는 injectEndpoints로 호출하면 된다.
대신 overideExisting은 false로 해야한다. 그래야 endpoint가 재정의되지 않는다.
Endpoints will not be overridden unless overrideExisting is set to true. If not, a development mode warning will be shown to notify you if there is a name clash between endpoint definitions.
자세한 내용 참조
https://redux-toolkit.js.org/rtk-query/api/created-api/code-splitting
API Slices: Code Splitting and Generation | Redux Toolkit
redux-toolkit.js.org
728x90
'코딩 > 전역 상태관리' 카테고리의 다른 글
[Justand] 전역상태관리 (0) | 2025.02.07 |
---|---|
[Redux] 리덕스 툴킷 redux-toolkit (0) | 2021.11.21 |
[Redux] 리덕스 정리 (0) | 2021.11.21 |
[Redux]리덕스 -Today I'm Learned (4) useCallback, useMemo (0) | 2021.02.03 |
[Redux]리덕스 -Today I'm Learned (3) 리덕스의 구성 (0) | 2021.02.02 |