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

Other Options for Delaying Execution in Node.js

Objective Exploring potential alternatives to improve the accuracy of timing functions in node.js, particularly focusing on a replacement for setTimeout. Background While developing a QPS (Queries Per Second) tester application, I encountered issues wit ...

When utilizing array.push() with ng-repeat, it appears that separate scopes are not generated for each item

I'm currently working on an Angular View that includes the following code snippet: <div ng-repeat="item in items track by $index"> <input ng-model="item.name"/> </div> Within the controller, I utilize a service to retrieve a Js ...

Oops! The module "rxjs/Subject" seems to be missing the exported member "Subject"

Here is the code I'm working with: import { Subject } from 'rxjs/Subject'; Upon importing this, an error occurs: rxjs/Subject" has no exported member 'Subject'. I am unable to fix this issue. Does anyone have a solution? ...

unable to execute PHP code

I am attempting to execute a PHP file that will update a database. On Chrome, I am encountering this error: This is the code I have in my index.html file: <!DOCTYPE html> <html> <body> <input type="text" id="descriptioninput"> ...

The issue with using useState on arrays is that it is not functioning properly with React Hooks

const [LatestNews, setLatestNews] = useState([]); useEffect(() => { async function fetchLatestData() { const result = await database.collection('latestnews').get(); result.docs.forEach(doc => ...

Comparison of efficiency in declaring JSON data using JSON.parse versus an object literal

In a recent video from the 2019 Chrome Dev Summit titled "Boosting App Speed with JSON.parse", it was revealed that utilizing JSON.parse with a string literal instead of an object literal can result in a significant enhancement in speed. The official Googl ...

Believing in false promises as true is what the statement assumes

I'm working on authentication for my app and encountered the following code: const ttt = currentUser.changedPasswordAfter(decoded.iat); console.log(ttt); if (ttt) { console.log('if thinks ttt is true'); The changedPasswordAfter fu ...

Implementing React and Firebase Firestore V9 for Paginating to the Initial Page after Navigating Back

I've hit a roadblock here. Despite following the exact steps outlined in various posts and tutorials, I'm still stuck. I know the importance of using a cursor to set the first and last visible document for moving forward or backwards. When moving ...

How can I bind the ID property of a child component from a parent component in Angular 2 using @Input?

I have a unique requirement in my parent component where I need to generate a child component with a distinct ID, and then pass this ID into the child component. The purpose of passing the unique ID is for the child component to use it within its template. ...

Make sure to save the HTML content after we make an AJAX call to retrieve it

Is there a way to call an HTML file using Ajax and then save the response as an HTML file in a specific location? I have been trying to make an Ajax call using jQuery, like shown below: $.ajax({ type: "POST", url: "../../../project/html/T ...

Using React-router-dom's Link component can cause styling inconsistencies with material-ui's AppBar Button

Exploring the use of a material-ui Button with react-router-dom's Link is showcased here: import { Link } from 'react-router-dom' import Button from '@material-ui/core/Button'; <Button component={Link} to="/open-collective"> ...

Incorporate unique color variables from the tailwind.config.js file

I am working on a project using nextjs and typescript, with tailwind for styling. In my tailwind.config.js file, I have defined some colors and a keyframe object. My issue is how to access these colors to use as background values in the keyframe. Here is ...

Executing asynchronous operations and handling responses in Node.js with Express

While I am still getting the hang of asynchronous functions and callbacks in Node.js, my current struggle lies in figuring out how to return a response after reading data from a file during an asynchronous operation. I have managed to send a response usin ...

What does the error message "TypeError: Bad argument TypeError" in Node's Child Process Spawn mean?

Every time I execute the code below using node: var command = "/home/myScript.sh"; fs.exists(command, function(exists){ if(exists) { var childProcess = spawn(command, []); //this is line 602 } }); I encounter this error: [critical e ...

Using Ajax to insert data into WordPress

Looking to incorporate data into the WordPress database using Ajax integration. functions.php function addDataToDB(){ global $wpdb, $count; $count = 25; $wpdb->insert( 'custom_table', array( 'slid ...

Error message: Discord bot written in JS is unable to read the property 'execute' as it is undefined

I'm having trouble getting this code to work. Here is the main file snippet: const fs = require('fs'); bot.commands = new Discord.Collection(); const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith ...

How can I input text into separate tabs using a specific method?

I've been struggling with this issue for a while now and here's the code I have so far: <html> <head> <script src="http://mihaifrentiu.com/wp-content/themes/mf/js/jquery_1.7.1.min.js" type="text/javascript"></scr ...

Getting the Request Body Content in Express Middleware

Currently, I am in the process of developing a small API logger to use as an Express middleware. This logger is designed to gather data from both the request and response objects, then store this information in a JSON file on disk for later reference. Her ...

Develop a custom BuyMeACoffee feature for Gatsby JS

I am currently working on developing a Buy Me A Coffee React component to include in my Gatsby website. Despite successfully running and building my Gatsby site in development mode, I am encountering an issue where the Buy Me A Coffee widget does not displ ...

Issue with populating labels in c3.js chart when loading dynamic JSON data

Received data from the database can vary in quantity, ranging from 3 to 5 items. Initially, a multi-dimensional array was used to load the data. However, when the number of items changes, such as dropping to 4, 3, 2, or even 1, the bars do not populate acc ...