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 => {
...
};
};
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
...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.