typescriptreduxnext.jsredux-thunknext-redux-wrapper

Next.js: getServerSideProps not working using Next.js with Next-redux-wrapper with TypeScript


When I'm trying to dispatch action as in documentation from the getServerSideProps using next-redux-wrapper store and redux-thunk i keep getting the following typescript error:

ts(2322): Type '({ req }: GetServerSidePropsContext<ParsedUrlQuery>) => Promise<void>' is not assignable to type 'GetServerSideProps<any, ParsedUrlQuery>'.
  Type 'Promise<void>' is not assignable to type 'Promise<GetServerSidePropsResult<any>>'.
    Type 'void' is not assignable to type 'GetServerSidePropsResult<any>'.

My code is as follows:

// category.tsx

export const getServerSideProps = wrapper.getServerSideProps(
    (store) =>
        async ({ req }) => {
            await store.dispatch(fetchCategory())
        }
)
// categoriesAction.ts

export const fetchCategory = () => {
    return async (dispatch: Dispatch<CategoriesAction>) => {
        try {
            const res = await axios.get("/category")
            dispatch({
                type: CategoriesActionTypes.LOAD_CATEGORY_SUCCESS,
                payload: res.data,
            })
        } catch (err) {
            dispatch({
                type: CategoriesActionTypes.LOAD_CATEGORY_ERROR,
                payload: err.code,
            })
        }
    }
}
// store.ts

const makeStore = (context: Context) =>
    createStore(reducer, composeWithDevTools(applyMiddleware(thunk)))

export const wrapper = createWrapper<Store<RootState>>(makeStore, {
    debug: true,
})
// reducers.ts

const rootReducer = combineReducers({
    categories: categoriesReudcer,
})

export const reducer = (state, action) => {
    if (action.type === HYDRATE) {
        const nextState = {
            ...state, // use previous state
            ...action.payload, // apply delta from hydration
        }
        if (state.count) nextState.count = state.count // preserve count value on client side navigation
        return nextState
    } else {
        return rootReducer(state, action)
    }
}

export type RootState = ReturnType<typeof rootReducer>

Solution

  • Your code

    // category.tsx
    
    export const getServerSideProps = wrapper.getServerSideProps(
        (store) =>
            async ({ req }) => {
                await store.dispatch(fetchCategory())
            }
    )
    

    Try this

    // category.tsx
    
    export const getServerSideProps = wrapper.getServerSideProps(
        (store) =>
            async ({ req }) => {
                try {
                    await store.dispatch(fetchCategory())
                    return { props: {} }
                } catch (e) {
                    return { props: {} }
                }
                
            }
    )