This commit is contained in:
grinikita
2024-12-14 12:32:32 +03:00
parent b997d670a0
commit 0ad224f04d
11 changed files with 191 additions and 32 deletions

29
src/store/api.ts Normal file
View File

@@ -0,0 +1,29 @@
// Need to use the React-specific entry point to import createApi
import { createApi, fetchBaseQuery, QueryReturnValue } from '@reduxjs/toolkit/query/react';
import { GetListResponse } from '../service/list/types';
import { listService } from '../service/list';
const createQueryFromPromise =
<ARGS, RES>(fn: (...args: Array<ARGS>) => Promise<RES>) =>
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async (...args): Promise<QueryReturnValue<RES, any, any>> => {
try {
const data = await fn(...args);
return { data };
} catch (e: unknown) {
return { error: e };
}
};
// Define a service using a base URL and expected endpoints
export const api = createApi({
reducerPath: 'api',
baseQuery: fetchBaseQuery({ baseUrl: '' }),
endpoints: (builder) => ({
getList: builder.query<GetListResponse, undefined>({
queryFn: createQueryFromPromise(() => listService.getList())
})
})
});
export const { useGetListQuery } = api;

20
src/store/index.ts Normal file
View File

@@ -0,0 +1,20 @@
import { configureStore } from '@reduxjs/toolkit';
import { api } from './api';
import { setupListeners } from '@reduxjs/toolkit/query';
export const store = configureStore({
reducer: {
// Add the generated reducer as a specific top-level slice
[api.reducerPath]: api.reducer
},
// Adding the api middleware enables caching, invalidation, polling,
// and other useful features of `rtk-query`.
middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware)
});
setupListeners(store.dispatch);
// Infer the `RootState` and `AppDispatch` types from the store itself
export type RootState = ReturnType<typeof store.getState>;
// Inferred type: {posts: PostsState, comments: CommentsState, users: UsersState}
export type AppDispatch = typeof store.dispatch;