I'm trying to dispatch a thunk
from the getServerSideProps
in Next.js using next-redux-wrapper
store. However, I keep getting the following typescript error:
TS2345: Argument of type '(dispatch: any) => Promise<any>' is not assignable to parameter of type 'AnyAction'. Property 'type' is missing in type '(dispatch: any) => Promise<any>' but required in type 'AnyAction'.
I haven't used TypeScript with Redux before, so not sure what I'm doing wrong here...
My code is as follows:
// page.tsx
export const getServerSideProps = wrapper.getServerSideProps(
async ({ store, params }) => {
store.dispatch(myThunkFunction(params.id));
return {
props: {
id: params.id,
},
};
});
// thunks.ts
export const myThunkFunction = id => {
return async dispatch => {
...
};
};
Next.js & Redux. I assume that if you landed here, then you should already know what Next.js and Redux are. For those who don’t: Next.js is a framework for painless React app development, capable of server rendering. Redux is a data framework that implements so called Flux paradigm, which, in turn, is a unidirectional data flow.
Next.js provides out-of-the-box support for server-side rendering of your page without any extra configuration from your part. There are two methods of Pre-Rendering a page when using Next.js. Methods of pre-rendering with next.js
The only challenge working with Redux is the initial Redux setup with server-side rendering and this is exactly what the following part covers. The official documentation, Redux provides a good explanation of how server-side rendering is expected to work with Redux. The explanation states that:
This function according to the next docs is responsible for: Next.js comes with getInitialProps, which is an async function that can be added to any page as a static method. getInitialProps allows the page to wait for data before rendering starts. Using getInitialProps will make the page opt-in to on-demand server-side rendering.
It seems to be a known issue with next-redux-wrapper
when using redux-thunk
, where the dispatch
type returned by next-redux-wrapper
in getServerSideProps
(or getInitialProps
as that is what I'm using) isn't a ThunkDispatch
.
I spent a lot of time trying to figure out what the issue was and managed to find a work around by creating an application thunk dispatch type like
export type AppThunkDispatch = ThunkDispatch<ApplicationState, void, AnyAction>
And when using it inside getServerSideProps
(or getInitialProps
) you would just cast the store.dispatch
to it.
const thunkDispatch = store.dispatch as AppThunkDispatch
I haven't tried it with getServerSideProps
but I'm assuming the store passed to it will be the same as the store passed to getInitialProps
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With