useMultipleQueries
#2398
-
I'm trying to make a general hook for making subscribing/selecting in multiple queries at once because we do a lot of that in our app. What I've come up is working but the problem is that I can't get the result typed correctly. I'm no TS-ninja so I appreciate any support 🙂 export const useMultipleQueries = <T, R>(
endpoint: ApiEndpointQuery<
QueryDefinition<T, any, any, R, any>,
EndpointDefinitions
>,
options: (T | SkipToken)[]
) => {
const dispatch = useAppDispatch();
useEffect(() => {
const subscriptions = options
.filter((options): options is T => {
return options !== skipToken;
})
.map((options) => {
return dispatch(endpoint.initiate(options));
});
return () => {
for (const subscription of subscriptions) {
subscription.unsubscribe();
}
};
}, [dispatch, endpoint, options]);
return useAppSelector((state) => {
return options.map((options) => {
return endpoint.select(options)(
state as any
) as QueryResultSelectorResult<QueryDefinition<T, any, any, R, any>>;
});
});
};
// Intended usage:
const user1And2Posts = useMultipleQueries(myApi.endpoints.getPosts, [{user: 1}, {user: 2}]); |
Beta Was this translation helpful? Give feedback.
Answered by
phryneas
Jun 10, 2022
Replies: 1 comment 3 replies
-
You know how to NerdSnipe:tm: me. I've started implementing a full-fledged version of this - I was kinda putting that off for a very long while. Since I don't have a lot of time atm.: cooperation is highly welcome, it's far from done right now. |
Beta Was this translation helpful? Give feedback.
3 replies
Answer selected by
hornta
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You know how to NerdSnipe:tm: me.
I've started implementing a full-fledged version of this - I was kinda putting that off for a very long while.
Since I don't have a lot of time atm.: cooperation is highly welcome, it's far from done right now.
#2402