Search code examples
javascriptredux-toolkitrtk-query

Is it possible to pass queryFn to useQuery?


As stupid as it sounds, my queryFn is taken from the context:

const fetch = useAppFetch()

I can't change this for historical reasons, so I'm wondering if it's possible to pass in queryFn when using it?

const fetch = useAppFetch()
const { data } = useDynamicQuery(
  { ...args },
  { queryFn: React.useCallback((args) => fetch(args), [fetch]) }
})

Solution

  • It's a bizarre design pattern but sometimes we've got to make things work.

    It seems like you figured out the implementation, based on your comment:

    @Philisonstrike Yes, I've tried passing queryFn as a parameter, but I get a warning: "A non-serializable value was detected in the state" , which works, but doesn't seem to be the recommended way.

    What I'm not understanding is how you are getting a non-serializable value in your state. You will inevitably have a non-serializable value in your action but that's not a problem (it's solved by thunk middleware).

    Are you are storing the queryFn argument in the state somehow? The default implementation of the serializeQueryArgs API option should have handled removing it. The only way I can imagine this being the cause is if you're already setting your own serializeQueryArgs option and it's not serializing everything.

    It seems more likely that the queryFn itself is returning its data in a non-serializable format. In which case your bizarre setup it's really the culprit.

    You need to track down the details of where and what this non-serializable value is and go from there.

    You haven't shown your implementation so I don't know what issues might be occurring there.