-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[Question] : Generic solution for prefetching paginated queries #4149
Comments
You can somewhat unsafely skip some steps using type predicates: import { Middleware, ThunkDispatch, UnknownAction, isFulfilled } from '@reduxjs/toolkit';
import { myApi } from 'src/api/enhancedApi';
import { RootState } from './store';
const hasEndpointName = (arg: any): arg is { endpointName: string } =>
typeof arg?.endpointName === "string";
const hasPage = (arg: any): arg is { originalArgs: { page: number } } =>
typeof arg?.originalArgs?.page === "number";
const fetchNextPageMiddleware: Middleware<
unknown,
RootState,
ThunkDispatch<RootState, unknown, UnknownAction>
> =
({ getState, dispatch }) =>
(next) =>
(action) => {
if (
isFulfilled(action) &&
hasEndpointName(action.meta.arg) &&
hasPage(action.meta.arg)
) {
dispatch(
myApi.util.prefetch(
action.meta.arg.endpointName as any,
{
...action.meta.arg.originalArgs,
page: action.meta.arg.originalArgs.page + 1,
},
{},
),
);
}
return next(action);
}; Ultimately though, unless you maintain a list of possible endpoints, it will be difficult to prove to Typescript that endpointName is correct (hence the as any) |
@EskiMojo14 Very cool thanks, I've also manage to not use any. However, I am more bothered of something else. |
no, the action will be identical to other fetches. |
Would it be ok to add that |
Thanks for helping! |
Hey!
So I have an Api object generated by RTKQ-Codegen. There is a large amount of endpoint and most of them have server-side pagination (i.e
page
andpageSize
parameters).I would like to know if it's possible to implement a generic solution (maybe a middleware?) to prefetch the next page of any query that have been fulfilled, if it had a
page
argument.Something like :
However I got some typing issues because action is of type
unknown
. Which means I have to manually check each property.The
dispatch
also doesn't allow me to actually dispatch the prefetch because the later returns aThunkAction
The text was updated successfully, but these errors were encountered: