How to get the url parameter in Nextjs

Asked

Viewed 685 times

3

Guys, I have a question on Next JS, I have a page with name listid.js, when accessing for example http://localhost:3000/listid/10 I would like to receive id 10 as parameter on my page listid.js:

import React, { useState, useEffect } from 'react';

// components

import ListUser from "components/ListUser.js";

function ListId() {
  
  return (
    <>
      <div className="flex flex-wrap mt-4">
        <div className="w-full mb-12 xl:mb-0 px-4">
          <ListUser />
        </div>
      </div>
    </>
  );
 
}

export default ListId;

Follow the code of my compound ListUser:

import React, { useState, useEffect } from 'react';
import Api from "../../services/api";
import Router from 'next/router';
import Link from "next/link";


function ListUser() {

  const [user, setUser] = useState(null);

  useEffect(() => {
    async function getItems() {
      try {
        const { data } = await Api.get("/user"); //preciso passar o parametro aqui
        setUser(data);
      } catch (error) {
        console.log(error);
      }
    }
    getItems();
  }, []);

  // console.log(users.length);
  if (users === null) {
    return <h2>Carregando...</h2>;
  }
  return (
    <>
        <div>
            {
              user?.map((user) => {
                return (
                    <p>{user.id}</p>
                )})
            }
        </div>
    </>
    );
}
export default ListUser;

How can I get the id in the url and pass the api request?

1 answer

2


For you to have this URL format http://localhost:3000/listid/10 just create inside the pages directory following this format: listid/[id].js where listid would be a folder with the page [id].js within.

And to get the parameter back id you can use the useRouter of the nextjs itself on the page [id].js and access the object query:

import { useRouter } from 'next/router'

...

const { query } = useRouter()

console.log(query.id)

Having recovered the id of the object query you can use it normally to perform the request.

Official documentation:

Any route like /post/1, /post/abc, etc. will be Matched by pages/post/[pid].js. The Matched path Parameter will be sent as a query Parameter to the page, and it will be merged with the other query Parameters.

Translation

Any route such as /post/1, /post/abc, etc. will be matched by pages/post/[pid].js. The corresponding path parameter will be sent as a query parameter to the page and will be merged with the other query parameters.

References:

Dynamic Routes

  • 1

    Thank you very much Gabriel, your explanation was of great help, I managed to do here!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.