Exploring the Dynamic Routing Features of Next.js

After diving into Next.js, I found the learning curve to be manageable since React was already familiar territory for me.

Currently, my focus is on implementing dynamic routing in my application -

Starting with my live/index.js file - (Where I utilize getServerSideProps to fetch initial data from an external API)

import Link from "next/link";

export async function getServerSideProps() {
    // Retrieve data from external API
    const res = await fetch(`https://api.pandascore.co/matches/running?sort=&page=1&per_page=50&token=#`)
    const data = await res.json()
    const games = data;

    // Pass data to the page through props
    return {
        props:
        {

            results: games,
        }
    }

}

const liveGames = ({ results }) => {
    return (
        <div>
            <div className="game-container">
                <h2>Live Games NOW - </h2>
                {results.map((q) => (
                    <Link href = {'/live/' + q.slug}key={q.slug}>
                       <a className="live_link"> <h3>{q.name}</h3></a>
                    </Link>
                ))}
            </div>
        </div>
    )
}

export default liveGames;

Next up, my live/[slug].js file - (Here I display more details about each game upon click)

export const getStaticPaths = async () => {
    const res = await fetch(`https://api.pandascore.co/matches/running?sort=&page=1&per_page=50&token=#`);
    const data = await res.json();

    const paths = data.map(o => {
        return {
            params: { slug: o.slug.toString() }
        }
    })
    return {
        paths,
        fallback: false
    }
}

export const getStaticProps = async (context) => {
    const slug = context.params.slug;
    const res = await fetch(`https://api.pandascore.co/matches/running?search[slug]=${slug}&token=#`);
    const data = await res.json();
    console.log(data)

    return {
        props: {
            game: data
        }
    }
}
const live = ({ game }) => {
    return (
        <div>
            <p></p>
            <h1>{game.name}</h1>
            <h1>{game.id}</h1>
        </div>
    );
}

export default live;

Overall, everything seems to be functioning as intended. My index page is properly routed and the URLs are generated based on the slug. I'm even receiving data in my console from [slug].js. However, the return() statement isn't rendering any content at all, and I'm struggling to identify the root cause without any error messages or clues.

I also have a query regarding the use of getServerSideProps in index.js and getStaticPaths in [slug].js. Will this potentially lead to CORS issues in production or is it considered acceptable practice? (Given my limited experience with Next.js, I was advised by my API provider to handle all API requests on the server side using Next.js).

Answer №1

After some investigation, I finally pinpointed the problem to a minor issue. The solution turned out to be quite simple - I just needed to re-map through the array in the [slug].js file. Now, everything is functioning perfectly according to my requirements.

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

JavaScript treats string as a primitive value

When it comes to JavaScript, a String is considered a primitive value. However, it can also be treated as a String object. In programming terms, a primitive value refers to a value assigned directly to a variable. This raises the question: var d = "foo"; ...

Tips for resolving the issue of invalid functions as a child component in React

When I call a function that returns HTML code, everything works fine until I try to pass a parameter in. At that point, I receive an error saying "Functions are not valid as a React child." The issue is that I need to access the props from this function. T ...

How to resolve a TypeError saying "Object(...) is not a function"?

I've been attempting to display material-ui tabs as a component on another page, but I'm encountering an error that causes the code to break when loading the page with this component. I've tried two different methods of rendering this compo ...

Trigger a series of functions upon clicking with ReactJS

Need some assistance with an alert message functionality. I have a button labeled Checkout, and when clicked, it should clear the cart and display an alert. At present, the individual functions work as expected - calling emptyCart() works fine, and calling ...

Query about Javascript/Node/JSON - why isn't this functioning properly?

I thought I had a good grasp on what I was doing until the process started getting jumbled. My code is being executed through Node, not a web browser. For some reason, it jumps to the prompt at the end of the while loop first and I'm not sure why tha ...

Implementing a smooth camera movement in Three.js using the mousewheel

Is there anyone who can assist me with achieving smooth camera movement (forward/backward) using the mouse wheel? The current code I have is not providing the desired smoothness. document.addEventListener( 'mousewheel', onDocumentMouseWheel, fal ...

Ensuring the successful execution of all AJAX calls (not just completion)

I've seen this question asked many times about how to trigger a function once all AJAX calls have finished. The typical solution involves using jquery.stop(). However, my situation is unique - I want to display a confirmation banner only after all AJA ...

React components are failing to display data as expected

I need to display certain data based on the id provided in the url. When I use console.log() with res.json, I can see the data but I'm unsure how to pass it to the 'articleComponent'. const Articles = () => { const query = (id) => ...

Failure occurred when attempting to link and display on the page container

I have created a simple app using jQuery Mobile. At some point in the app, I include the following code: <a href="test_es.html" data-role="button">Start!</a> This code snippet loads a new HTML file that contains several jQuery Mobile page ...

Can you assist me with setting a value in an ASP dropdownlist?

I have an asp dropdownlist and I need to set its value from the client side. Although I am able to retrieve the data from the client side, I am facing difficulty in setting it in my asp dropdownlist using JavaScript. HTML <div class="col-md-6 form-gro ...

Is there a way in Angular to activate the contenteditable feature through a controller?

I have a collection of items, and the currently selected one is displayed in more detail on another section of the screen. The detailed section allows users to modify specific parts of the chosen item using contenteditable. When a user adds a new item to ...

Updating a connected model in Sequelize using another model

Seeking guidance on updating a model with new associations in Sequelize. The model involves a many-to-many relationship with a join table. Attempted this code snippet: app.patch('/api/team/:id/newplayers', function(request, response){ const pl ...

Executing a series of HTTP requests sequentially using Angular 5

I need some guidance on sending an array of HTTP requests in sequential order within my application. Here are the details: Application Entities : Location - an entity with attributes: FanZone fanZone, and List<LocationAdministrator> locationAdmins ...

Node.js used to create animated gif with unique background image

As I navigate my way through the world of node.js and tools like express and canvas, I acknowledge that there might be errors in my code and it may take me some time to grasp certain concepts or solutions. My current project involves customizing a variati ...

JavaScript: How to identify and select a specific item from a context menu

Currently diving into the world of JavaScript, so please keep that in mind when explaining. My main goal is to figure out a way to detect when a user triggers a right-click or uses the context menu from the keyboard. Specifically, I want to know if they s ...

What are the issues with using AJAX in conjunction with a for-loop?

I'm currently developing a small application that needs to create work schedules and calculate hours: . I've written the function kalkulacja() to calculate the inputs for each row and output the results through ajax. However, I'm facing an i ...

How can I use jQuery to either display or hide the "#" value in a URL?

I have a question that I need help with. Let's say I have the following links: <a href="#test1"> Test </a> <a href="#test2"> Test 2 </a> When I click on Test, the URL will change to something like siteurl/#test1. However, whe ...

Tips for choosing option values from the browser console in Angular

Is there a way to choose one of the list values directly from the browser console? I appreciate any assistance provided <select style="width: 100%" id="Select1" class="css-dropdowns ng-not-empty ng-dirty ng-valid ng-valid-required n ...

Having trouble with nodeJS when running the command "npm install"?

Can anyone help me understand why I'm encountering issues when running "npm install"? Whenever I run npm install, I am bombarded with numerous errors. npm ERR! Windows_NT 10.0.10586 npm ERR! argv "C:\\Program Files\\nodejs&bsol ...

The container is not showing the JSTree as expected

My current project in JavaScript involves integrating a JSTree structure, but I'm encountering an issue where the tree is not showing up or rendering within its specified parent container. Below is the snippet of code I have been using to attempt to d ...