What is the best way to send additional data with getServerSideProps() in Next.js?

Not sure if this is a silly question, but I am currently working with a Django API and attempting to implement pagination on the search page using Next.js. As a newbie to Next.js, I have scoured the web for a solution but haven't found anything helpful yet. The error in my code seems to indicate that passing both "context" and "query: {page = 1}" simultaneously might not work. Is there a way around this issue?

import Video from '../../components/video'

const VideosSearch = ({results: videos, page}) => {
    return(
        <>
        <div>
            {videos.length > 0 && videos.map ((video) =>
            <Video key={video.id} {...video} />)}
        </div>
        <button onClick={() => router.push(`/videos?page=${page + 1}`)}> next </button>
        </>
    )
}

export async function getServerSideProps(context, {query: {page = 1}}){
    const start = +page === 1 ? 0 : (+page - 1) * 3
    const res = await fetch(`http://localhost:8000/api/videos/?offset=${start}&ordering=-list_date&search=${context.params.query}`)


    const json = await res.json()
    const videos = json
    return{
        props: {
            results: videos.results,
            page: +page
        }
    }
}

export default VideosSearch

It's throwing me an error that says:

TypeError: Cannot read property 'query' of undefined

By the way, this code snippet is from /pages/search/[query].js

Answer ā„–1

When working with the context object, you have access to both params and query. Only one context parameter is received by getServerSideProps with multiple keys.

For example, if you have a file named /pages/search/[query].jsx that supports URLs like /search/sith or /search/sith?page=2

You can make modifications as shown below:

export async function getServerSideProps(context) {
    const page = context.query.hasOwnProperty('page') ? parseInt(context.query.page, 10) : 1;

    const start = (page - 1) * 3;

    console.info(context.params.query, page, start);

    const res = await fetch(`http://localhost:8000/api/videos/?offset=${start}&ordering=-list_date&search=${context.params.query}`)

    const json = await res.json()
    const videos = json;

    return{
        props: {
            results: videos.results,
            page: page
        }
    }
}

Answer ā„–2

The context parameter actually contains all the necessary information you require.

export async function getServerSideProps(context) {...}

To retrieve a parameter from the URL, you can follow these steps:

const { page, query}= context.req.params

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

Animation loading on React.js when the page or URL is changed

Just starting out with React and trying to incorporate a loading animation when the page/url changes on button click - check it out here: https://codesandbox.io/s/cthululel-7zmsl?fontsize=14 Successfully got the animation working on initial load, but runn ...

Switch up the autofill hue for Stripe checkout using NextJS

We are implementing Stripe's Element payment feature with NextJS. We have extracted and utilized only the relevant part related to element payments from this link. In order to change the background color when filling in the credit card number using a ...

The cache does not contain '.chunk-`X`' as requested in Next.js error

Hello everyone, I've encountered a recent issue with my code that previously worked fine. I was using getStaticProps with a cache time of 5 days, but now I'm facing an error related to the title. Here is a more detailed look at the error: error ...

Webstorm seems to be having trouble identifying Next.js

When I create a Next.js app using the command npx create-next-app my-app --use-npm Everything is successfully installed, but when using WebStorm, I noticed that it does not auto import the <Link> component from Next.js. I have to manually import it ...

Using local variables from an external HTML file within an AngularJS directive template

Just making sure I am wording my question correctly, but I have not been able to find any information on this specific topic. Imagine I have an AngularJS directive that looks something like this: angular.module( 'example', [] ).directive( ...

"I'm experiencing an issue where my JSON data is not displaying in the browser when I run the code

I am having trouble displaying my json data in the browser. This is my first time working with json and I can't seem to identify the issue. I tried researching online and found that it could be related to mime types, but I still can't solve it. B ...

Discovering an Element in jQuery through its ID using Spaces and Variables

My issue involves locating an element within another element using an ID and then adding a class when the ID is hardcoded. For example: var tableId = el.id; $('#' + tableId).find("[id='Checkout On']").addClass('highlight'); ...

Despite encountering an error in my terminal, my web application is still functioning properly

My code for the page is showing an error, particularly on the home route where I attempted to link another compose page The error message reads as follows: Server started on port 3000 Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after t at new Node ...

What is the best way to display a loading indicator on a Next.js page?

At times in Next.js, there can be a delay in loading a page without any visual cues to show that the page is changing after triggering a <Link /> click or using router.push. Imagine being on a dictionary website looking at a word definition. You the ...

What is the best way to manage error handling in various locations within an Angular stream?

Currently, I am working on ensuring that errors are handled properly in a stream where the id of a group is retrieved first and then used to obtain profile information. I want to easily identify whether the error is occurring during the retrieval of the g ...

Vuefire encountering an issue with Vue 3 and throwing a Vue.use error

After setting up a Vue app and importing Vue from the vue module, I encountered an issue: ERROR in src/main.ts:4:5 TS2339: Property 'use' does not exist on type 'typeof import("/data/data/com.termux/files/home/ishankbg.tech/node_modules/vue/ ...

Using FastAPI and React to manage anonymous user sessions

In my current project, the backend is built with FastAPI and the frontend with React. I am looking to create an anonymous user session upon visiting the site and include that session ID in each API call. This session should be able to update the user' ...

The functionality of Vue is acting up with the HTML, unexpectedly refreshing when a button is clicked

I am currently experiencing an issue with my Vue application. When I click the button, it clears the input field (which it shouldn't) and doesn't perform any other actions. The variables "codigo" and "payload" do not display anything on the scree ...

Dynamically attach rows to a table in Angular by triggering a TypeScript method with a button click

I need help creating a button that will add rows to a table dynamically when pressed. However, I am encountering an error when trying to call the function in TypeScript (save_row()). How can I successfully call the function in TypeScript and dynamically a ...

What are the ways to enable VS Code's Intellisense to collaborate with AngularJS's injected services?

Hey, I've been trying to get Visual Studio Code to provide me with its intellisense for my unique framework (not Angular) app's services. Although I managed to get the standard type for such frameworks, I'm struggling to find a solution for ...

Updating the background image without having to validate the cache

I have implemented a basic image slideshow on my website using a simple Javascript function. The function runs every 5 seconds to update the CSS "background-image" property of a div element. While it is functional, I've noticed that each time the func ...

Save a randomly generated string in the Session, which will be replaced when accessed through a different PHP file

I have created a form with a hidden input field, and its value is dynamically set using a function. <?php class Token { public static function generate(){ return $_SESSION['token'] = base64_encode(openssl_random_pseudo ...

Handle TRPCError with TRPC

I am currently developing an application using Next.js and TRPC. I have encountered an issue where, when a query is made with TRPC and an error occurs, the client side does not receive the error. This is my Page: "use client" import { useRouter ...

Error! D3.js is throwing an Uncaught TypeError because it cannot find the function .enter(...).append(...).merge

Currently, I am facing an issue while attempting to construct a table with multiple nested dropdowns using d3.js. The problem arises when switching from a newer version of d3 where my code functions flawlessly to d3.js v3. Upon replacing the newer version ...

Having trouble getting sweet alert to work with my PHP script

Iā€™m integrating Sweet Alerts 2 into my webpage in order to prompt the user when trying to delete something. However, I'm encountering an issue where the PHP file is not being triggered when the user presses delete and the Sweet Alert does not appear ...