Tips for retrieving the slug value in getStaticProps for invoking the API with the slug as a parameter

Content on the Page:

import { useRouter } from "next/router";
    
export default function Daily({ data }) {
    let router = useRouter()
    
    const { slug } = router.query;
    return slug;
}

And display on the page 60d6180ea9284106a4fd8441 (https://.../gunluk/60d6180ea9284106a4fd8441 id in URL)

I can retrieve the ID but I am unsure how to pass it to the API.

export async function getStaticProps(context) {
    const res = await fetch(`http://localhost:3000/api/books-i-have`)
    const data = await res.json()
    
    if (!data) {
        return {
            notFound: true,
        }
    }
    
    return {
        props: { data }, // will be passed to the page component as props
    }
}

Usually, I use this method but it didn't work with the slug. I attempted other methods as well but they were unsuccessful (https://nextjs.org/docs/basic-features/data-fetching).

In essence, how do you establish a connection to the API from the Slug page?

File directory:

    pages/
        gunluk/
            [...slug].js
            index.js

Answer №1

To retrieve the slug value within getStaticProps and utilize it for making API calls based on the slug, you can follow these steps:

export async function getStaticPaths() {
    const idList = await fetchAllIds();
    const paths = [];
    idList.forEach((id) => { paths.push(`/gunluk/${id}`) })
    return { paths, fallback: true };
}

export async function getStaticProps({ params }) {
    const { slug } = params;

    try {
        const data = await fetchGunluk(slug);
        return data ? { props: { data } } : { notFound: true };
    } catch (error) {
        console.error(error);
        return { notFound: true };
    }
}

Answer №2

Here is an example of code that I executed in my Next.js project:

  const router = useRouter();
  const slug = router.query.course_slug;
  console.log(slug); //displaying the value of the slug variable

Answer №3

It seems like the solution you need can be found in the getStaticPaths

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

Transferring information from JavaScript to PHP

I am trying to send both the data and text that are within a single DIV tag using JavaScript into PHP values. However, I am encountering an issue with the following code: <html> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jq ...

Circular arrangement using D3 Circle Pack Layout in a horizontal orientation

I'm currently experimenting with creating a wordcloud using the D3 pack layout in a horizontal format. Instead of restricting the width, I am limiting the height for my layout. The pack layout automatically arranges the circles with the largest one ...

Is there a way for me to adjust the typography background based on its current status?

Is there a way to dynamically adjust the background color of text based on the status value? Currently, when the status is pending, the background color defaults to yellow. For example, if the status changes to complete, I want the background color to ch ...

Allow users to zoom in and out on a specific section of the website similar to how it works on Google Maps

I am looking to implement a feature on my website similar to Google Maps. I want the top bar and side bars to remain fixed regardless of scrolling, whether using the normal scroll wheel or CTRL + scroll wheel. However, I would like the central part of the ...

There seems to be an issue with the CSS file linking properly within an Express application

Every time I run my app.js file, the index.html file is displayed. However, when I inspect the page, I notice that the CSS changes are not taking effect. Strangely, if I open the HTML file using a live server, the CSS changes are visible. Can someone exp ...

The specified property 'XYZ' is not found in the type 'Readonly<{ children?: ReactNode; }> & Readonly<{}>'

Whenever I try to access .props in RecipeList.js and Recipe.js, a syntax error occurs. Below is the code snippet for Recipe.js: import React, {Component} from 'react'; import "./Recipe.css"; class Recipe extends Component { // pr ...

Pressing the icon will trigger a top-sliding dropdown mobile menu to appear

How can I ensure my mobile dropdown menu slides in from the top when the user clicks the "header-downbar-menu" icon and slides out to the top when clicked again? Currently, the button only shows the menu but I am struggling with writing the JavaScript for ...

Having trouble with Node.js multiparty upload functionality

I'm facing an issue with the functionality of multiparty.Form(). Specifically, I am attempting to print numbers like 2, 3, and 4. Below is the code snippet for uploading images: app.post('/gallery/add',function(req, res,next) { var input = ...

One of the unique CSS properties found in the NextJS setup is the default 'zoom' property set to

Even though I already found a solution to the problem, I can't help but wonder what the author meant by it. Hopefully, my solution can help others who may encounter the same issue. After installing the latest NextJS version 13.2.4 on my computer, I e ...

Sorry, but React does not accept objects as valid children. Make sure the content you are passing is a valid React child element

I encountered an issue with rendering on a screen that involves receiving an object. The error message I received is as follows: Error: Objects are not valid as a React child (found: object with keys {_U, _V, _W, _X}). If you meant to render a collection o ...

Issue: setAllcategories function not found

Currently engaged in using Next.js and Sanity as a Headless CMS for the backend. In the code snippet below, I have created a Categories.js file in the components folder to fetch some data. My objective is to extract all the titles from the category Array. ...

Incorporating HTML5 Video Using an AJAX Request

I am attempting to fetch a video using an ajax query, but it seems that the video player control buttons are missing. Here is the code I am using: $.ajax({ context: document.body, url: "/?get=json&act=video", type: "get", success: fu ...

Is it possible to pass a parameter to an NGXS action that is not the Payload?

I am working on implementing an Ngxs action that includes a parameter in addition to the payload. This parameter is used to determine whether or not a notification should be sent. @Action(UpdateUser) async UpdateUser( ctx: StateContext<ProfileStat ...

Looking to extract the first URL from a string using JavaScript (Node.js)?

Can someone help me figure out how to extract the first URL from a string in Node.js? " <p> You left when I believed you would stay. You left my side when i needed you the most</p>**<img src="https://cloud-image.domain-name.com/st ...

Adding and deleting MPEG-DASH segments from a media source buffer in a dynamic manner

I have been developing a custom MPEG-DASH streaming player using the HTML5 video element. Essentially, I am setting up a MediaSource and attaching a SourceBuffer to it. After that, I am appending DASH fragments into this sourcebuffer and everything is func ...

Setting up the environment variable for ApolloClient to be utilized in server-side rendering for continuous integration/continuous deployment involves following a specific

My apolloClient is configured as follows: /** * Initializes an ApolloClient instance. For configuration values refer to the following page * https://www.apollographql.com/docs/react/api/core/ApolloClient/#the-apolloclient-constructor * * @returns Apoll ...

After selecting an item, the Next UI navbar menu seems to have trouble closing

Having trouble with the navbar menu component not closing when an option is selected from the menu. The menu does open and close successfully within the menu icon. I attempted to use onPress() but it doesn't seem to be working as expected. "use c ...

Using NextJS router to navigate and scroll to a specific component on a different page

Imagine I find myself on Page1 and there is a button that triggers a router.push to Page2. However, my dilemma arises when I need Page2 to automatically scroll to a specific component upon loading. Is this even possible? Does anyone have any insights or ...

Creating a flexible route path with additional query parameters

I am facing a challenge in creating a unique URL, similar to this format: http://localhost:3000/boarding-school/delhi-ncr However, when using router.push(), the dynamic URL is being duplicated like so: http://localhost:3000/boarding-school/boarding-school ...

What are alternative ways to divide CSS without relying on CSS-in-JS and CSS modules?

Recently, I transitioned to next.js and I'm eager to develop an application with CSS styles without resorting to css-in-js or inline styling. In my exploration, I've come across two potential options: using CSS modules or importing global styles ...