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

Could this be a problem within my recursive function?

Struggling to iterate through a stack of HTML Elements, I attempted to write a recursive function with no success. In the code snippet below, I'm facing challenges in returning a value from an if statement and ultimately from the function itself. Wh ...

Automatically inserting a row into an HTML table

My table structure looks like this: <form name="frm_data_nasabah2" method="post" enctype="application/x-www-form-urlencoded" action="<?php echo $page_action;?>"> <table class="table table-bordered table-hover" id="tab_logic_ ...

Is there a way to directly update the value of a nested object array using v-model in VUE?

Looking to update a value in JSON using v-model { class: "data.child", "myform.input1": [true, "<input1 value>"] } <input type="text" v-model="<what should be inserted here?>" > //update the value directly in my ...

How do I use the data fetched in getServerSideProps to update the state of React Context in Next.js?

Struggling with properly loading data into state for my todo app has been quite the challenge. In my todo app, I have a next.js page component located in pages/index.tsx. Here, I fetch data from my API using getServerSideProps and pass it to the component ...

Update all items in the menu to be active, rather than only the chosen one

Here is the layout of my menu along with the jQuery code included below. The functionality is such that when I click on Home Page, its parent element (list item) receives an active class. Currently, when I am on the Home Page, the list item for Account Co ...

The React Functional Component undergoes exponential re-renders when there is a change in the array

I'm encountering a problem with one of my functional components. Essentially, it maintains an array of messages in the state; when a new message is received from the server, the state should update by adding that new message to the array. The issue ar ...

What methods are available for generating a short-lived banner using JavaScript?

I recently entered this industry and am in the process of constructing a website. Utilizing HTML and CSS, I crafted a cookie notification banner. I am seeking guidance on how to ensure that it only appears once "every 24 hours for each user." I attempted ...

Troubleshooting jQuery: Unable to refresh the webpage

I have a PHP page that contains a form, checkboxes, and a submit button. I added an if statement to execute a PHP script I created when the button is clicked, which deletes certain values from the selected rows. The button functions properly and changes s ...

How can I add navigation dots to my slider?

I've been experimenting with my slider and I managed to make it slide automatically. However, the issue is that there is no option to manually navigate through the slides. I am looking to add navigation dots at the bottom so users can easily switch be ...

Display the hidden div element when clicked

In my code, I have two div elements as follows: <div class='staticMap'></div> <div class='geolocation-common-map'></div> Initially, the 'geolocation-common-map' div is removed using jQuery when the pa ...

Masking Aadhaar numbers

I need to find a way to detect when the back button is pressed on an input field. The methods I have tried, e.key and e.which, are returning as undefined in mobile Chrome. How can I make this work? It's functioning properly on desktop. jQuery(funct ...

Angular reactive form encountered an issue with an incorrect date being passed

Currently, I am utilizing the PrimeNg calendar module to select a date. Here is the code snippet: <p-calendar formControlName="valid_till" [dateFormat]="'mm/dd/yy'"></p-calendar> Upon selecting a date like 31st J ...

What is the best way to empty input, select, and textarea fields after performing a clone operation

I am currently working on creating a form to display items and need a fresh text field when the user clicks the ADD button. function addNewItem() { //ADD ROW AND CLONE var table = document.getElementById('tbl'); var tbody = document.create ...

My NextJS page is missing the essential hreflang meta tags

I am facing an issue where the SEO checker tools like are unable to detect my generated HREFLANG tags. These tags are being generated within my language switcher component inside the next/head component. My assumption is that the problem might be related ...

PHP encountered an issue when retrieving a value from a URL and passing it to a JavaScript variable

How can I pass a PHP variable from the URL using $_REQUEST to JavaScript in order to send it through Ajax? Here is the code snippet at the top of my page: <?php include_once('../php/connection.php'); include_once('../php/getDiagnosi ...

Protractor experiencing difficulty in adjusting price slider

As a newcomer to protractor, I am attempting to test a price slider that sorts products based on the provided price range. Unfortunately, I am facing difficulty in dragging the slider (min point) using protractor. Can anyone provide guidance on how to move ...

Eliminate any properties with values that exceed the specified number in size

:) I'm trying to create a function that removes properties with values greater than a specified number. I've searched through multiple resources like this question on how to remove properties from a JavaScript object and this one on removing pro ...

Modifying the status using retrieved JSON information

My goal is to retrieve data from an external API and use it to update the state of my app. Although I can see the data in the console, the state of my app remains unchanged when I try to run setState. class App extends Component { state={ jobs:[] ...

An action in redux-toolkit has detected the presence of a non-serializable value

When I download a file, I store it in the payload of the action in the store as a File type. This file will then undergo verification in the saga. const form = new FormData(); if (privateKey && privateKey instanceof Blob) { const blob = new Blo ...

Using Selenium: Checking for existing dropdown values and incrementing if necessary

I am currently working on automating an application using Selenium Webdriver with Java. The web application I am testing has an Add button that, when clicked, triggers the activation of a dropdown menu. Subsequent clicks on the Add button reveal additional ...