Troubleshooting issue with getServerSideProps not functioning in Next.js while utilizing Next-redux-wrapper and TypeScript

When attempting to trigger an action as outlined in the documentation using the getServerSideProps function with the help of next-redux-wrapper store and redux-thunk, I am encountering 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>'.

The code snippet causing the error is shown below:

// 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>

Answer №1

Your solution

// category.tsx

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

Give this a shot

// category.tsx

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Receiving a 405 error when making an API call - could the routing be misconfigured? (Using NextJS and Typescript)

Hey there, I've been working on implementing a custom email signup form that interfaces with the Beehiiv newsletter API. If you're interested, you can take a look at their API documentation here: Beehiiv API Docs Currently, my web application i ...

Encountering a TypeScript error in MUI 5 when attempting to spread values in props

I am encountering an issue with a typescript error related to the MUI sx prop. The problem arises when I attempt to merge or spread multiple sx values into an sx prop, resulting in an error. It seems to work fine if only one item is present in the sx prop, ...

Strategies for monitoring user login activity in NextAuth to display a button

After exploring, I discovered that Next Auth offers various methods for tracking user authentication. By utilizing useSession (Client-based) Through getServerSession (Server-based) Now, suppose I want to display login and logout buttons based on the user ...

Ways to ensure Nextjs reads head tags

I have added head tags in both my _app.tsx and _document.tsx pages for my nextjs app (with react v18). However, I am facing an issue where the browser tab is not updating with the title or favicon specified in those Head tags. In app.tsx, the code looks ...

Learn how to use Angular2 or TypeScript to display 'unsubscribe' and 'subscribe' text on a toggle button

I'm working on a toggle button that initially displays the word subscribe on the thumb. When the toggle is disabled, I want it to show unsubscribe instead. Can someone please help me achieve this functionality? Here's the code snippet: <md-s ...

The ant layout slider collapsible feature is unable to be utilized in conjunction with SSR in NextJs

Incorporating antd into my NextJs app, I have implemented a Layout component at the top level of my application. /* _app.tsx */ function MyApp({ Component, pageProps }: AppProps) { return ( <Provider store={store}> <SideMenuLayout> ...

After the installation of Storybook, there is a duplicate identifier error that arises with 'LibraryManagedAttributes'

Upon running the command npx storybook@latest init for setting up Storybook, which results in modifying package.json, I encounter an issue where I cannot run the project using npm due to: Error: node_modules/@types/react-dom/node_modules/@types/re ...

Using NEXT JS, Three js is able to convert an equirectangular panorama into cubemap format

I'm currently working on converting an equirectangular panorama image into cubemap format using NEXT JS. The scene is being rendered but I'm facing an issue where the background isn't applying, and surprisingly, no errors are showing up! im ...

Tips for effectively implementing a curried selector function with the useSelector hook in react-redux

In my project using react-redux with hooks, I encountered a situation where I needed a selector that takes a parameter which is not passed as a prop. Upon checking the documentation, it mentioned: The selector function does not receive an ownProps argum ...

The FormControl is currently presenting ",required(control)" within its value field

Upon loading my form, the default values in the input fields are set to: ,required(control) { return isEmptyInputValue(control.value) ? { 'required': true } : null; } The template structure of my form is as follows: <form [formG ...

Exploring the capabilities of Redux Toolkit's createEntityAdapter in designing versatile data grids

Seeking guidance on utilizing createEntityAdapter from Redux Toolkit. In my application, I display package information and details using the master/detail feature of the AG Grid library. Packages are loaded initially, followed by fetching detailed data as ...

Updating the latest version of Typescript from NPM is proving to be a challenge

Today, my goal was to update Typescript to a newer version on this machine as the current one installed is 1.0.3.0 (checked using the command tsc --v). After entering npm install -g typescript@latest, I received the following output: %APPDATA%\npm&b ...

The code below is not working as it should be to redirect to the home page after logging in using Angular. Follow these steps to troubleshoot and properly

When looking at this snippet of code: this.router.navigate(['/login'],{queryParams:{returnUrl:state.url}}); An error is displayed stating that "Property 'url' does not exist on type '(name: string, styles: AnimationStyleMetadata". ...

Is it possible for Angular2 to map a lone JSON object?

Dealing with a JSON response that is a single object, rather than an array, can be tricky. Recently in my project, I encountered a situation where I needed to map and use such a response from an API to fill out a template. It seemed like a simple task at f ...

Ways to confirm if the indexed sort is an extension of a string

Suppose I have a function called func with 2 generic arguments const func = <T extends {}, K extends keyof T>() => {}; and a type defined as interface Form { a: boolean; b: string; } then I can call them without encountering any errors func& ...

Tips for incorporating asynchronous page components as a child element in next.js?

Utilizing the latest functionality in next.js for server-side rendering, I am converting my component to be async as per the documentation. Here is a simple example of my page component: export default async function Home() { const res = await fetch( ...

Why does the API in Next Js get triggered multiple times instead of just once, even when the strict mode is set to false?

React Query Issue I am currently facing an issue with React Query where the API is being triggered multiple times instead of just once when the selectedAmc value changes. I have tried setting strict mode to false in next.config.js, but that didn't so ...

What is the process for creating a personalized user interface for NextAuth.js that integrates with AWS Cognito?

Can I create a unique user interface for AWS Cognito with NextAuth.js? Whenever I use the NextAuth.js API, I am presented with a rather unattractive screen containing just a button that redirects to the actual AWS Cognito sign-in page. Although the AWS Co ...

Issue with accessing custom method in subclass in Typescript

Recently delving into TypeScript, I decided to subclass Error and add a new method called getCode() in my MyError class. export class MyError extends Error { public code: number; constructor(code: number, message?: string) { super(mes ...

Angular 2 Quickstart encountered a 404 error when trying to retrieve the /app/main.js

I'm attempting to follow the Angular 2 quickstart guide, but I'm having trouble getting it to work. I've searched for similar questions but haven't found a solution yet. Can anyone assist me with this? Here is my code: app.component.t ...