Should queryFn(fetcher) be independent of React life cycle?
I'm working on a Next.js 14 project (App Router) and need to set up a centralized axios instance as queryFn(fetcher) in order to use react-query, which should integrates seamlessly with:
1. useSession from next-auth
2. i18n from next-intl:
3. router from next/router
4. A React modal component
I have come up with two approaches:
1. A function returned from a custom React hook
2. A standalone, React-independent function
What do you guys think? What's the right way to go about it?
6 Replies
correct-apricot•8mo ago
Definitely #2. You might need to fire an XHR request outside of React, and there's no reason to trap yourself into a react hook.
evident-indigoOP•8mo ago
But I have some trouble getting the token using getSession from next-auth. For every outgoing request I make, it also makes an api call to my nextjs server for getting the session.
correct-apricot•8mo ago
I'm not super familiar with Next, but I would suggest handling the session itself within React. Wrap your app in a context provider, and have that context intercept the axios requests and manage session state within React.
evident-indigoOP•8mo ago
but I need to add the token(from session) to the header of every request sent to API server(separated from nextjs server). If my fetcher is independent of react, then I won't be able to get the session from context provider
correct-apricot•8mo ago
Let me grab a copy of our implementation
This generates a RestClientPort object that can receive additional interceptors.
This may be a bit more formal than is strictly necessary, but I need this dang codebase to last 5+ years of active development
unwilling-turquoise•8mo ago
Are you on next auth v5?
I think number 1 is fine, the hook works since you have dependency on react hooks like the router