One of the great features of Next.js is its ability to easily change

At the moment, my dynamic path is configured to display events by their ID [id].js localhost:3000/event/1

But I would like it to be structured as follows: localhost:3000/city/date/title. All of this information is available in the events database, but I'm struggling to figure out the correct approach for this.

[id].js

export const getStaticPaths = async () => {
  const { data: events } = await supabase.from("events").select("id");
  const paths = events.map(({ id }) => ({
    params: {
      id: id.toString(),
    },
  }));

  return {
    paths,
    fallback: "blocking",
  };
};

export const getStaticProps = async ({ params: { id } }) => {
  const { data: events } = await supabase
    .from("events")
    .select("*")
    .eq("id", id)
    .single();

  return {
    props: {
      events,
    },
    revalidate: 60,
  };
};

Answer №1

If you're in search of nested dynamic routes,

Consider structuring your directories like this:

/
   [city]
      [date]
         [title]

For instance, for the URL: localhost:3000/paris/25-12/event, your params object should be :

{ "city": "paris", "date": "25-12" , title : "event" }

Implement it with:

export const getStaticProps = async ({ params: { city , date, title } }) => {

Furthermore, don't forget to update getStaticPaths. The returned params will include all keys and the code may resemble:

export async function getStaticPaths() {
    let paths = await someAsyncMethod();
    //convert paths into an array structured as 
    //{   params : { city : '' , date : '' , title : ''} }[]

    return {
        paths : paths,
        fallback: false
      } 
 }

Answer №2

After experimenting with different approaches, I found a solution that worked for me:

  const { data, error } = await supabase
    .from("events")
    .select("city, date, title");

  const paths = data.map((event) => ({
    params: {
      city: event.city,
      date: event.date,
      title: event.title
  }));

  return { paths, fallback: false };
}

export const getStaticProps = async ({ params }) => {
  const { data, error } = await supabase
    .from("events")
    .select("*")
    .eq("city", params.city)
    .eq("date", params.date)
    .eq("title", params.title);

  return {
    props: {
      events: data[0],
    },
  };
};

Although there may be other methods, this is the approach that ultimately resolved my issue.

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

Angular in conjunction with socket.io does not immediately show messages on screen

I am currently working on developing an instant messaging app (chat) using socket.io and Angular. I have two main files: index.html and index.js as shown below. The chat functionality is working well, but I am facing an issue where the messages do not appe ...

Troubleshooting JavaScript directly on the client side

As a JavaScript beginner hoping to transform into a JavaScript expert, debugging is an essential skill I must master. Currently, I am utilizing Chrome debugger tools to tackle a complex array of spaghetti JavaScript code that resembles a cryptic puzzle wai ...

What is the best way to display the tabcontent when clicking on a menu tab in this code, as neither method seems to work?

Take a look at my JSFiddle demo: <http://jsfiddle.net/xrtk9enc/2/> I suspect that the issue lies within the javascript section. My html code includes an Unordered List that serves as the tab menu. Each href of the menu corresponds to a tab content, ...

Embed Vue applications within the container of the main Vue application

My goal is to establish a foundational Vue application that offers essential features such as signing in, navigating with a sidebar, and the flexibility to interchange navbar items. I envision creating separate Vue applications for each navbar item. Main ...

How can this JSON function correctly?

Hey there! I've been trying really hard to receive a response from PHP and based on that response, perform different actions. However, I seem to be facing some challenges with handling the output from the PHP file. Below is a snippet of my index file: ...

TypeScript does not recognize the $.ajax function

Looking for help with this code snippet: $.ajax({ url: modal.href, dataType: 'json', type: 'POST', data: modal.$form.serializeArray() }) .done(onSubmitDone) .fail(onSubmitFail); ...

Attaching a buoyant div to the precise location of a different element

I have a unordered list (ul) with individual list items (li) that are displayed within a scrollable container. This means that only 8 list items are visible at a time, but you can scroll through them to see the others. Each list item (li) has an "edit" b ...

Creating a dropdown menu in Bootstrap 4 using JSON information

I am trying to create a dynamic drop-down menu using an input field with a drop-down button inside a form. Currently, I am attempting to populate the drop-down menu with static JSON data. However, I am encountering issues with getting it to function proper ...

Unable to view videos shared by users in PeerJS and WebRTC video chat application from different tabs

Recently, I embarked on the task of creating a Video chat Website using Peer Js. Initially, everything seemed to be working fine as I was able to see my own video stream. However, a problem arose when attempting to view the video stream from another tab or ...

`There is a delay in rendering the background image on Chrome`

Once I apply a class to my button element using JavaScript, the background image (.gif) that is supposed to display afterwards takes an unusually long time to render. The button serves as a form submission. Upon being clicked, a class of "clicked" is dyna ...

Unable to interpret data from JSON file

I have written the following code to read a JSON file. It is not throwing any errors, but I am receiving a null value in the variable: var myData = null; $.ajax({ type: 'GET', async: false, url: 'myJson.json', dataType: ...

React is struggling to dynamically update text content using button click events

As a beginner in the world of React, Nodejs, and JavaScript, I am exploring onClick events to dynamically change text by clicking buttons. In my practice project, I have an input type="checkbox" that toggles the text between bold and normal style ...

Use jQuery's change method to initiate a hidden file input

Want to create a fake file input using an anchor tag and trigger the hidden file input with jQuery? Looking for some advice on how to make this happen. Check out my current attempt here. I'm not sure if I'm on the right track with this, so any g ...

What is the best way to identify the type of an element using AngularJS?

Is it possible to use ng-model to identify the type of an element? For example: How can we determine if a specific element is a dropdown or a checkbox? HTML Code Snippet <select multiple ng-model='p.color'> <option value="red">Re ...

Stanza.io encountered difficulties in generating a WebRTC answer

I have successfully set up a realtime messaging website using ejabberd + stanza.io. Everything works perfectly, and now I want to integrate Webrtc audio/video using the jingle protocol. Below is the JS code I am using for connection: var client = XMPP.cre ...

Why isn't the length of the Array changing when using React's useState hook

I am facing a challenge trying to understand why the value of inputElementArray.length consistently remains 0 when accessed within the useEffect method. function view() { const [inputElementArray, setInputElementArray] = useState<HTMLInputElement[]& ...

Tips on searching for an entry in a database with TypeScript union types when the type is either a string or an array of strings

When calling the sendEmail method, emails can be sent to either a single user or multiple users (with the variable type string | string[]). I'm trying to find a more efficient and cleaner way to distinguish between the two in order to search for them ...

What is the process for setting up basic http authorization using angular.js?

My backend setup follows a structure similar to what is explained in this article. I am looking to make a GET request using angular.js, just like curl does it, with authorization via HTTP headers: $ curl -u miguel:python -i -X GET http://127.0.0.1:5000/a ...

Display a hidden form field in Rails depending on the object's value

As a programmer learning Ruby on Rails without much knowledge of Javascript, I faced a problem with a form that creates an object called Unit. This Unit model is related to Category which in turn is related to Product. The issue was that while selecting a ...

Trouble arises when jquery's "position().top" clashes with the CSS3 property "transform: scale()"

Currently, I am working on adding a font resizer feature to my editing tool. To implement this, I made some changes to the text elements where their origin is now set to the bottom left corner. The normal version of the tool works perfectly fine, but when ...