Getting access to state inside of queryFn
#2217
-
Hi guys, At work we have an old codebase using Sagas. We need to move that across to new Redux methods. After some research, I like the way Redux Query works. It will make our code much shorter.
Here is what I have tried so far: export const userApi = createApi({
reducerPath: 'userApi',
baseQuery: fetchBaseQuery({ baseUrl: 'https://base.url' }),
endpoints: (builder) => ({
loginUser: builder.mutation({
queryFn: (args, queryAPI) => {
try {
const [ , { data } ] = customerAPI.useCheckCustomerMutation(); // invalid hook call error
} catch (error) {
console.log(error);
}
return { data: '' };
},
}),
}),
}); And I have also tried: export const userApi = createApi({
reducerPath: 'userApi',
baseQuery: fetchBaseQuery({ baseUrl: 'https://base.url' }),
endpoints: (builder) => ({
loginUser: builder.mutation({
queryFn: (args, queryAPI) => {
try {
const state = queryAPI.getState(); // this gets all the state and we need requestID to get the associated data
} catch (error) {
console.log(error);
}
return { data: '' };
},
}),
}),
}); This second way seems closer to what I want to get. The issue is that it returns the whole state. Then I need to know what's the requestID to get the data of that mutation. How can I get access to that requestID? or is there an easier way? Thanks for the help |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
I figured out a way needs more work on the types but it works for now. I have to see if it works consistently or not for the time being. I'm not sure how it would act if we trigger many of that export function getEndpointData<T>(state: any, reducerPath: string, endpointName: string) {
const mutations = Object.values(state[reducerPath].mutations)
const selectedMutation: any = mutations.find((m: any)=> (m.status === 'fulfilled' && m.endpointName === endpointName));
return (selectedMutation ? selectedMutation.data : []) as T;
} Keen to know what do you guys think? |
Beta Was this translation helpful? Give feedback.
-
What are you actually trying to do? I'm quite sure you have a XY Problem here - you found out So: |
Beta Was this translation helpful? Give feedback.
What are you actually trying to do? I'm quite sure you have a XY Problem here - you found out
queryFn
exists and now you're building a lot of logic in there - but from what you are writing here I am not sure if you are even using the right tool.So:
Can you please explain what your actual goal is, not what you need after applying some different approaches to your initial goal already?