Error encountered in Next.JS when calling getInitialProps(ctx) due to undefined ctx variable

This is my code

import NavLayout from "../../components/Navigation/Navigation";

export default function WorldOfWarcraft({ game }) {
    return (<NavLayout>
        {game.link}
    </NavLayout>)
}

WorldOfWarcraft.getInitialProps = async (ctx) => {
    const response = await fetch(`http://localhost:6969/favGames/${ctx.query.id}`);
    const game = await response.json();

    return { game };
}

I have a similar code on another 'page' and it functions correctly. This piece of code is exactly the same, just with different identifiers, yet it does not work as expected. When attempting to log ctx, it returns as undefined. Additionally, this code is part of 'index.js'

import Link from "next/link";
import NavLayout from "../../components/Navigation/Navigation";

export default function FavGames({ games }) {
    console.log(games);
    return (<NavLayout title={'Fav Games Page'}>
        <h1>Favorite Games</h1>
        <ul>
            {games.map(game => (
                <li key={game.id}>
                    <Link href={`/fav-games/[games]`} as={`/fav-games/${game.id}`}>
                        <a>
                            {game.title}
                        </a>
                    </Link>
                </li>
            ))}
        </ul>
    </NavLayout>);
}

FavGames.getInitialProps = async () => {
    const response = await fetch('http://localhost:6969/favGames');
    const games = await response.json();

    return { games };
}

In essence, I am dynamically linking from index.js to [games].js file. However, the issue lies in why ctx is returning as undefined :(

Answer №1

After struggling for two whole days, I finally cracked the code. It turns out the solution was right in front of me all along. The culprit was a tiny detail in this snippet of code:

 <Link href={`/fav-games/[games]`} as={`/fav-games/${game.id}`}>

The key lies in replacing [games] with the correct value. Instead of using

const response = await fetch(`http://localhost:6969/favGames/${ctx.query.***id***}`);

it should actually be:

const response = await fetch(`http://localhost:6969/favGames/${ctx.query.***games***}`);

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

Attach an event listener to a particular textarea element

Currently, I am developing a project in Next.js13 and my focus is on creating a custom textarea component. The goal is to have this component add an event listener to itself for auto-adjusting its height as the user types. Below is the relevant section of ...

I'm currently facing an issue where the Ionic styles are not displaying correctly within my Next.js application

I'm currently experiencing a problem where Ionic styles are not being applied to certain pages in my Next.js app. Despite working on the home page, the Ionic styles do not seem to be taking effect on the profile page. Any guidance on troubleshooting t ...

Socket.io-powered notification system

I'm currently in the process of developing a notification system for my Events Manager Website. Every time a user is logged in and performs an action (such as creating an event), a notification about the event creation should be sent to other user ...

Converting JSON data into an array of a particular type in Angular

My current challenge involves converting JSON data into an array of Recipe objects. Here is the response retrieved from the API: { "criteria": { "requirePictures": true, "q": null, "allowedIngredient": null, "excluded ...

How to implement a feature for uploading multiple files through a single form with unique input fields in a web

After searching on Stack Overflow, I couldn't find a suitable solution for my problem. I need help with my code that fetches data and sends it to a PHP file to upload files to specific folders and store their links in a database. However, I am encount ...

Capture the onclick attribute with jQuery and then reapply it

I am facing a challenge with a page that has several calendars composed of HTML tables where each day is represented by a td. The td elements have an onClick attribute which I need to manipulate using jQuery. Specifically, I need to remove the onClick attr ...

Tips for sending form data from ReactJS to controller in ASP.NET MVC:

Seeking help with React and ASP.NET integration. I am attempting to create a form in ASP.NET using React, but encountering issues when trying to pass form data from ReactJS to an MVC ASP.NET controller. Below is the code that I have been working on. Any su ...

Revolutionary scroll-based navigation fill transition

I'm attempting to achieve an effect where the fill color of the "insticon" SVG changes from black to white based on the scroll position indicated in the jQuery code. I have made the necessary modifications in the if and else statements, but unlike "he ...

Storing multiple values of dynamically added elements in a single variable and accessing them within a function

Is it possible to store multiple values into a single variable and then access them in a setTimeout function? $(document).ready(function (){ div ({'div':'#noo','auto':'true','pos':'top',' ...

Running a <script> tag with an external src attribute in a dynamic manner through the use of eval

Currently, I am utilizing the Genius API to fetch lyrics for a particular song and then embed them within an HTML <div> tag. My interaction with this API is through PHP, employing an AJAX GET request. Upon a successful AJAX request, the following HT ...

Mouseover function not triggering until clicked on in Google Chrome

I'm attempting to execute a function when the cursor hovers over a list item as shown below: <div id="vue-app"> <ul> <li v-for="item in items" @mouseover="removeItem(item)">{{item}}</li> </ul> </div> ...

Obtain your access token from auth0

Currently, my setup involves utilizing auth0 and nextJS. My objective is to have the user redirected to the callback API after successfully logging in with their credentials. Here is the snippet of code I am working with: import auth0 from '../. ...

Which is more efficient: filtering a JSON object or querying the database using ajax?

I am currently developing a product page that involves a selection of options that will impact the pricing of the items. The primary option allows users to choose a material, which then influences the available set of options. Within the database, there i ...

Partial display issue with SweetAlert popup

I am currently working on a personal project using ASP.NET MVC5 and incorporating SweetAlert for managing message alerts. However, I have encountered an issue where the alert message only appears for a brief moment when testing it on an HTML5 button with t ...

Having trouble integrating an HTML template using JavaScript

I am currently attempting to integrate the HTML code of my website using data-prototype: <div id="accordion" data-prototype=' <div class="card-body"> <textarea id="solution_answers___name___content" name=& ...

Tips for changing the first letter to uppercase in a p5.js variable

I'm currently working on developing a weather forecasting website using the p5.js framework in JavaScript. One issue I am facing is that the API I am utilizing only provides weather descriptions in lowercase format, whereas I want them to be displayed ...

Stop the inheritance of CSS and JavaScript in ASCX files

Currently, I have an application that consists of only one aspx page called Default.aspx. This page dynamically loads .ascx controls as required, all of which utilize the same JS and CSS file. I am now considering implementing Bootstrap on specific control ...

ReactJs: Struggling to programmatically set focus on an element with React.createRef()

Looking to detect when a user clicks on an arrow using the keyboard? I stumbled upon the Arrow Keys React react module. To make it work, you need to call the focus method on a specific element. Manually clicking on an element does the trick: https://i.s ...

Webpack generates unique hashed file names for images within the project

Within one of the components located in my client/components directory, I have imported three images from the public/images folder. Recently, webpack generated hashed files for each image such as: 0e8f1e62f0fe5b5e6d78b2d9f4116311.png. Even after deleting t ...

Retrieve the text from an ajax response that includes the <tag> element

I have created a simple piece of code to fetch news from an RSS page. Below is the code snippet: this.loadRecentNews = function loadRecentNews() { $.get("http://rss.nytimes.com/services/xml/rss/nyt/GlobalHome.xml", function (data) { ...