The function getServerSideProps does not return any value

I'm a beginner with Next.js and I'm currently using getServerSideProps to retrieve an array of objects. This array is fetched from a backend API by utilizing the page parameters as explained in the dynamic routes documentation: https://nextjs.org/docs/api-reference/data-fetching/get-server-side-props

Once I have the array, I pass it on to another component for mapping.

However, upon running the application, I encounter an error message that reads:

TypeError: Cannot read properties of undefined (reading 'page')

I'm puzzled as to why this issue is occurring since the backend server appears to be sending the objects correctly.

Below is the code snippet for the Page component:

export interface LikedListRes {
    LikedArtwork: SearchResult[]
    page: number
}

const Account: NextPage<{data: LikedListRes}> = ({data}: {data: LikedListRes}) => {
    return (
        <Grid container spacing={2}>
            <Grid xs={4} sm={4} md={4} lg={4}></Grid>
            <Grid xs={8} sm={8} md={8} lg={8}>


                <Box sx={{margin: 'auto'}}>
                   <LikedArtworks page={data.page} likedArtwork={data.LikedArtwork} />
                </Box>


            </Grid>
        </Grid>
    )
}

Additionally, here is the function which includes the route using the userID parameter:

const getServerSideProps: GetServerSideProps = async ({params}) => {

    const getLikedArtwork = async (userID: string, page: number) => {
    const res = await fetch(`http://${api}/likedArtwork?page=${page.toString()}&userID=${userID}`).then(async res => {
        const response: LikedListRes = await res.json()
        return response 
    })

        return res
    }

    const res = await getLikedArtwork(params?.id as string, 0)

    return {
        props: {data: res}
    }


}

If anyone has any suggestions or insights on how to resolve this issue, your help would be greatly appreciated!

Answer №1

After some investigation, I finally cracked the code. It turns out that you need to export the function in order for it to work properly.

export const getServerSideProps: GetServerSideProps = async (context) => {...

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

What is the process for including a unique attribute for child elements within a React component using TypeScript?

I have a component that creates a Table of Contents (TOC) and List for the child elements. These children can be any JSX.Element. Here is an example... <SectionScrollList> <View key="first"/> <View key="second"/> ...

Using line breaks in JSX

In my application, I save all the text in a settings.ts file. However, I am facing an issue where \n does not seem to add line breaks as expected. Are there any alternative methods to include breaklines in my text? My tech stack includes Next.js, Reac ...

Result of Mongodb aggregation operation

I've created a Property controller : //Retrieve Properties By Type const getPropertiesByType = async (req: Request, res: Response) => { const { cities, type } = req.query; const citiesArr = typeof cities === 'string' ? cities.spli ...

Tips for customizing an image within the antd upload component

Using the upload feature within an antd form component has presented me with a challenge. <Form name="posting" onFinish={onSubmitForm} scrollToFirstError encType='multipart/form-data' > <Form.Item name=&qu ...

The Typescript compiler will continue to generate JavaScript code even if there are compilation errors

As a fresh learner of TypeScript, I have been experimenting with some basic concepts. Below is the code from my file app1.ts: class Monster { constructor(name, initialPosition) { this.name = name; this.initialPosition = initialPosition ...

How to disable click event binding in Angular2 after it has been clicked once

Within my application, there is a button that has a click event attached to it: <button class="btn btn-default" (click)="doSomething()"> I am wondering if there is a way to remove the (click) event from the button within the doSomething method so t ...

Struggling to figure out webhooks with Stripe

I have encountered a strange issue while using Stripe webhooks to process payments on my website. When I set the currency to USD, it prompts me to provide an address outside of India, which is expected. However, when I change the currency to INR, the addre ...

Attempting to display two separate d3 line graphs within a single Ionic2 page

I am facing an issue with including multiple similar graphs on a single page within an Ionic2 application. I am utilizing the d3-ng2-service to wrap the d3 types for Angular2. The problem arises when attempting to place two graphs in separate div elements ...

Getting data from components in React: A step-by-step guide

As a newcomer to Reactjs, I find myself working on an existing project where I am attempting to retrieve product reviews using components. However, my console currently displays 0 reviews. How can I resolve this issue? The file in question is "pages/[slug ...

Unit testing Jest for TypeScript files within a module or namespace

Recently, I've joined a mvc.net project that utilizes typescript on the frontend. There are numerous typescript files wrapped within module Foo {...}, with Foo representing the primary module or namespace. All these typescript files are transpiled in ...

Calling gtag("event") from an API route in NextJS

Is there a way to log an event on Google Analytics when an API route is accessed? Currently, my gtag implementation looks like this: export const logEvent = ({ action, category, label, value }: LogEventProps) => { (window as any).gtag("event&quo ...

Prevent click events on disabled tabs in PrimeNG tabMenu

I am encountering an issue with PrimeNG's p-tabMenu when it comes to disabled menu items. For example, suppose I have a tabMenu with 4 sub tabs labeled AAA, BBB, CCC, and DDD. This is how the menuItems are set up in the TypeScript component: //.... ...

Error message in Angular 2: Unable to locate node module for import

Recently, I encountered an issue while attempting to utilize a specific node module called aws-api-gateway-client Although the installation was successful, I am facing difficulties with importing this module due to an error. Oddly enough, it works seamle ...

Trouble with references in Vue TypeScript when trying to access child component methods

I'm encountering an issue with calling a function in a child component while using typescript <notification ref="notification"></notification> <button @click="$refs.notification.show()"></button> Is there a ...

Guidelines for returning an object upon finishing the .map function within a promise-based function in Node.js

While working on server-side code using nodejs, I have encountered an issue with the .map() method inside a Promise. The problem is that the method returns a value before the .map() function completes its execution successfully. Here's the snippet of ...

A tutorial on submitting multipart/form-data using JavaScript

I am currently facing an issue with the uploadImage API in my frontend. I am using input[type='file'] to obtain image data from users and then POSTing it to my API. In the backend, I am parsing this data using formidable. However, the problem ari ...

How to extract words from a dynamic router.pathname in NextJS when only the filename is displayed instead of the full path?

I'm keeping this example as straightforward as possible, but I can add more details if needed to solve the issue Currently, I am working with dynamic routes in nextJS. My application fetches data from Twitter based on the keywords entered into the dy ...

The coexistence of conflicting extensions, such as Metamask and Trust Wallet, both attempting to interact

I am working on developing a personal service that I want to integrate with browser extensions like Metamask and Trust Wallet, with the potential to include others in the future. However, I am facing challenges in finding resources on how to access the nec ...

Challenges encountered while using TypeScript to implement the CSS breakpoint mixin

I attempted to replicate the breakpoint mixin functionality described at using TypeScript, but I am having trouble correctly typing the function. import { css } from 'styled-components'; import { breakpoints } from './_variables'; exp ...

How can I maintain the router query when refreshing a page in Next.js?

I am facing an issue with a dynamic page and URL that is rendered on the client side. Below is the code snippet for the link that navigates to the second page: <Link href= {{ pathname: '/dashboard/[orderdetail]', query: { id: `${orderID}` } ...