Description
Good afternoon, I'm using rtk-query in my project, and I'm trying to do a refreshToken query following the “ https://redux-toolkit.js.org/rtk-query/usage/customizing-queries#automatic-re-authorization-by-extending-fetchbasequery” instructions.
There is a problem when I add injectEndpoints.
It scolds on
export const {useGetUserByIdQuery} = getProjectApi
The contents of the error are
'useGetUserByIdQuery' does not exist on type 'Api<BaseQueryFn<string | FetchArgs, unknown, FetchBaseQueryError>, { getUserById: QueryDefinition<{ userId: string; accessToken: string; }, BaseQueryFn<string | FetchArgs, unknown, FetchBaseQueryError>, never, any, “baseApi”>; }, “baseApi”, never, unique symbol>'.
Translated with DeepL.com (free version)
Below is the code,
import {createApi, fetchBaseQuery} from '@reduxjs/toolkit/query';
import type {
BaseQueryFn,
FetchArgs,
FetchBaseQueryError,
} from '@reduxjs/toolkit/query';
import {Mutex} from 'async-mutex';
// create a new mutex
const mutex = new Mutex();
// Base query function
const baseQuery = fetchBaseQuery({baseUrl: '/'});
const baseQueryWithReauth: BaseQueryFn<
string | FetchArgs,
unknown,
FetchBaseQueryError
> = async (args, api, extraOptions) => {
await mutex.waitForUnlock();
let result = await baseQuery(args, api, extraOptions);
if (result.error && result.error.status === 401) {
if (!mutex.isLocked()) {
const release = await mutex.acquire();
try {
const refreshResult = await baseQuery(
'/refreshToken',
api,
extraOptions,
);
if (refreshResult.data) {
// Here you should handle token updates, e.g., dispatch an action to store the new token
result = await baseQuery(args, api, extraOptions);
} else {
// Handle logout or other actions as needed
}
} finally {
release();
}
} else {
await mutex.waitForUnlock();
result = await baseQuery(args, api, extraOptions);
}
}
return result;
};
export const baseApi = createApi({
reducerPath: 'baseApi',
baseQuery: baseQueryWithReauth,
endpoints: () => ({}),
});
export const getProjectApi = baseApi.injectEndpoints({
endpoints: builder => ({
getUserById: builder.query<any, {userId: string; accessToken: string}>({
query: ({userId, accessToken}) => ({
url: `user.get?ID=${userId}`,
method: 'GET',
headers: {
Authorization: `Bearer ${accessToken}`,
},
}),
}),
}),
overrideExisting: false,
});
export const {useGetUserByIdQuery} = getProjectApi;