Skip to content

Commit

Permalink
feat(apiSlice): api slice with common modules, get and post
Browse files Browse the repository at this point in the history
  • Loading branch information
juunie-roh committed Jun 7, 2024
1 parent f389294 commit a8a8730
Show file tree
Hide file tree
Showing 4 changed files with 49 additions and 2 deletions.
2 changes: 1 addition & 1 deletion src/.next/cache/eslint/.cache_8hexeq

Large diffs are not rendered by default.

38 changes: 38 additions & 0 deletions src/libs/features/apiSlice.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';

const tagTypes = ['A', 'B', 'C'] as const;
type Tag = (typeof tagTypes)[number];
type Param = {
data?: Record<string, any>;
body?: Record<string, any>;
url: string;
tag: Tag;
};
// Query Builder
const buildQuery = (data?: Record<string, any>) =>
new URLSearchParams(data).toString();

export const apiSlice = createApi({
reducerPath: 'api',
baseQuery: fetchBaseQuery({ baseUrl: '/' }),
tagTypes,
endpoints: (builder) => ({
// Common Endpoints:
get: builder.query({
query: (param: Param) =>
param.data ? `${param.url}?${buildQuery(param.data)}` : param.url,
providesTags: (result, error, param) => [{ type: param.tag }], // Cash Provider Tags
}),
post: builder.mutation({
query: (param: Param) => ({
url: param.url,
method: 'POST',
body: param.body,
}),
invalidatesTags: (result, error, param) => [{ type: param.tag }], // Cash Invalidator Tags
}),
}),
});

// Export the auto-generated hook for the query endpoints
export const { useGetQuery, usePostMutation } = apiSlice;
1 change: 1 addition & 0 deletions src/libs/features/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from './apiSlice';
export * from './auth/authSlice';
export * from './catFacts/catFactsSlice';
export * from './counter/counterSlice';
10 changes: 9 additions & 1 deletion src/libs/store.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,22 @@
import { configureStore } from '@reduxjs/toolkit';

import { authReducer, catFactsReducer, counterReducer } from '@/libs/features';
import {
apiSlice,
authReducer,
catFactsReducer,
counterReducer,
} from '@/libs/features';

export const makeStore = () => {
return configureStore({
reducer: {
counter: counterReducer,
catFacts: catFactsReducer,
auth: authReducer,
[apiSlice.reducerPath]: apiSlice.reducer,
},
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().concat(apiSlice.middleware),
});
};

Expand Down

0 comments on commit a8a8730

Please sign in to comment.