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

Angular service is continuously throwing the error message "NullInjectorError: No provider for anotherService"

I recently built a basic Angular service and encountered an issue. @Injectable() export class someHandler { constructor( public anotherService: anotherService, ) {} ... The problem arises when I try to use this service in a component, as ...

Error occurred when sending form data while uploading a file

Upon trying to upload a file using the formData.append(key, value);, an error message is displayed in the value section: The argument of type 'unknown' cannot be assigned to a parameter of type 'string | Blob'. Type '{}' is ...

Issues with NativeScript WebView displaying HTML file

Having trouble loading a local HTML file into a webview in my NativeScript (typescript) application. Despite using the correct path, it's not loading and instead shows an error. <WebView src="~/assets/content.html" /> An error message stati ...

Building a Next.js dynamic page with useSWR data fetching strategy

I am trying to dynamically generate pages based on the ID of a Salon profile using useSWR and useRouter, but I am encountering an issue where the data loads after the pages have already been rendered. Below is my code snippet: import useSWR from "swr ...

Fast screening should enhance the quality of the filter options

Looking to enhance the custom filters for a basic list in react-admin, my current setup includes: const ClientListsFilter = (props: FilterProps): JSX.Element => { return ( <Filter {...props}> <TextInput label="First Name" ...

Data loss occurs when the function malfunctions

Currently, I am working with Angular version 11. In my project, I am utilizing a function from a service to fetch data from an API and display it in a table that I created using the ng generate @angular/material:table command. Client Model export interfac ...

Use CredentialsProvider to enable Next Auth login functionality

I am encountering an issue where I retrieve a user from the database and store it in a variable called result. However, I noticed that the result object does not contain the password key, resulting in the value of result.password being undefined. I am un ...

How to extract the first initials from a full name using Angular TypeScript and *ngFor

I am new to Angular and still learning about its functionalities. Currently, I am developing an Angular app where I need to display a list of people. In case there is no picture available for a person, I want to show the first letters of their first name a ...

What is the best way to transfer user data from the backend to the frontend?

I successfully created a replica of YelpCamp using Node and EJS, but now I am attempting to convert it into a Node-React project. Everything was going smoothly until I encountered an issue while trying to list a specific user in the SHOW route. In order to ...

Utilizing Highcharts pattern filling in a stacked column chart with Next.js

I've been working on integrating Highcharts into my Next.js project to create a column chart, but I'm facing an issue where the pattern-fill chart is not displaying. Removing the color: {} from the code below will make the chart visible. I'v ...

The 'posts' binding element is assumed to have a type of 'any' by default

Currently, I'm working on a code project that involves graphql, react, and typescript. In the middle of the process, I encountered an error message stating "Binding element 'posts' implicitly has an 'any' type." I am unsure about w ...

The specified target "TypeScriptClean" is not present within the project

I'm facing some issues in Visual Studio 2017 Professional. Despite not having any TypeScript code in my solution, I am encountering numerous TypeScript-related errors during the build process. The main error message that keeps popping up is: The targ ...

Troubleshooting problem with Chakra UI and NextJS hydration

Recently, I've been encountering the following error message: Error: Hydration failed because the initial UI does not match what was rendered on the server. Warning: Did not expect server HTML to contain a <a> in <div>. In my code snippe ...

Easiest Angular Carousel Solution

My goal is to create a basic Angular Carousel to enhance my understanding of Angular. While I have received helpful answers in the past, I am seeking further clarification to deepen my knowledge of Angular2+ and Typescript. Here's what I have so far: ...

Different ESLint configurations for mjs, js, and ts files

For my project, I've set up ESM (.mjs) files for server-side code, CommonJS (.js) for tooling, and TypeScript (.ts) for the client side. In VS Code, when I look at CommonJS files, I'm getting errors related to requires such as "Require statement ...

Utilizing Nginx reverse proxy to automatically refresh a NextJS application through PM2

I have successfully set up my NextJS application on Debian 12 using Nginx and PM2. Nginx serves as a reverse proxy, allowing my application to run smoothly. However, I am experiencing some issues with browsing pages. Whenever I try to navigate using rout ...

It appears that Next.js caches files in a route ending with _next/data/[path].json, which can prevent getStaticProps from executing during server-side rendering

When sharing a link on platforms like Discord and Slack, an issue arises where a URL preview is generated by sending a request to the link. The link structure in question is as follows: www.domain.com/ctg/[...ids]. https://i.stack.imgur.com/Nl8MR.png Wit ...

The state data is not being updated prior to making the fetch request

Currently delving into the world of Next.js and React after working with Angular/Svelte, I quickly put together a rough POC but encountered an issue where my data doesn't update. In this specific scenario, completed_at starts off empty when I submit ...

What is the best way to output data to the console from an observable subscription?

I was working with a simple function that is part of a service and returns an observable containing an object: private someData; getDataStream(): Observable<any> { return Observable.of(this.someData); } I decided to subscribe to this funct ...

Creating Angular models for complex nested JSON structures

I'm a beginner with Angular and I'm dealing with nested API responses from a Strapi application. I've set up a model using interfaces, but I'm having trouble accessing attributes from the product model when trying to access product data ...