Configuring Redux Thunk extra argument with Next.js Router
Unanswered
Japanese Bobtail posted this in #help-forum
Japanese BobtailOP
When configuring Redux Thunk middleware, you can provide an optional
But then I realized that
I'm wondering if it is worth it to finagle some sort of limited NextRouter API, like
Currently we're still using the pages router, but I would also like to keep the app router in mind, and not build something that's a huge headache for a future migration to the app router.
extraArgument, which will make that value available on the thunkApi that's provided to your thunk payload creator function. (See: https://github.com/reduxjs/redux-thunk#injecting-a-custom-argument). For example,export const buildStore = (router: NextRouter) =>
configureStore({
reducer,
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware({
thunk: {
extraArgument: { router },
},
})
})
export const Provider = ({ children }: PropsWithChildren) => {
const router = useRouter()
const storeRef = useRef<Store>()
if (!storeRef.current) {
storeRef.current = buildStore(router)
}
return (
<ReduxProvider store={storeRef.current}>
{children}
</ReduxProvider>
)
}
export const foo = createAsyncThunk(
'foo',
async (action, { dispatch, extra: { router } }) => {
// now you can call `router.push` here, among other async logic,
// side effects, and dispatching actions
},
)But then I realized that
const router = useRouter() is not referentially stable, and in the case of the pages router, it has properties like pathname, query, asPath, etc. that will go stale... so I don't think that's what we want.I'm wondering if it is worth it to finagle some sort of limited NextRouter API, like
Pick<NextRouter, 'push' | 'replace' | 'reload' | 'prefetch' | 'back'>, or maybe use import Router from 'next/router' instead of useRouter... or if this is all just a bad idea?Currently we're still using the pages router, but I would also like to keep the app router in mind, and not build something that's a huge headache for a future migration to the app router.
2 Replies
Japanese BobtailOP
I guess I can just use
import Router from 'next/router', which gives me a SingletonRouter, which (I'm assuming from the name) should be referentially stable, and has dynamic get property functions that will return updated properties like route, pathname, etc.The only issue is if depending on this could prove to be a future headache if we migrated to app router