Attempt to write a hook using addListener for any createApi instance #2474
-
Hello! I am trying to make a new functionality for subscribing to changes in the status of My const APISlice = createApi({
baseQuery: fetchBaseQuery({
baseUrl: "/api/v1"
}),
reducerPath: "APISlice",
endpoints: (builder) => ({
getUser: builder.query<{ user: string }, void>({
query: () => ({
url: "user"
})
})
})
}); Hook import { useEffect } from "react";
import { addListener } from "@reduxjs/toolkit";
import { useAppDispatch } from "../store";
import { APISlice } from "../store/api";
import type { AnyAction, ListenerEffect } from "@reduxjs/toolkit";
import type { RootStore, AppDispatch } from "../store/index";
type APISliceEndpoints = keyof typeof APISlice.endpoints;
type APISliceEndpointsMatchers = keyof Pick<
typeof APISlice.endpoints[APISliceEndpoints],
"matchPending" | "matchFulfilled" | "matchRejected"
>;
function useApiMiddlewareListener(arg: {
endpoint: APISliceEndpoints;
matcher: APISliceEndpointsMatchers;
effect: ListenerEffect<AnyAction, RootStore, AppDispatch>;
}) {
const dispatch = useAppDispatch();
useEffect(() => {
const unsubscribeFunc = dispatch(
addListener({
predicate: APISlice.endpoints[arg.endpoint][arg.matcher],
effect: arg.effect
})
);
return unsubscribeFunc;
}, [arg, dispatch]);
}
export { useApiMiddlewareListener }; Use export default function App() {
useApiMiddlewareListener({
endpoint: "getUser",
matcher: "matchFulfilled",
effect: (action, listenerApi) => {
// some logic inside component scope
}
});
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
} But there was an error typing the
For some reason, the error specifies a value for
I just wanted to explicitly specify the type for my ListenerEffect<AnyAction, RootStore, AppDispatch> Maybe someone can help me point out my mistake? Or should I stop trying to create such functionality altogether 😂 |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
I'd assume it's feasible, but I'm afraid I don't have time to actually look at the types behavior and figure out how to tweak things. |
Beta Was this translation helpful? Give feedback.
I'd assume it's feasible, but I'm afraid I don't have time to actually look at the types behavior and figure out how to tweak things.