Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

187
Visualizações
Is there a way for me to use the router.query in next js in a function?

So I have this Next.js page. I'm trying to use the request params and use it in a function, but for some reason it's always undefined. I've tried everything I know.

  • I know that I don't need to put the id in the function.
  • I tried using the router in useEffect, wouldn't work.

Here's my code :

import React, { useState, useEffect } from 'react'
import { useRouter  } from 'next/router'
import axios from 'axios';

export default function id () {
    const [ response, setResponse ] = useState("");
    const router = useRouter();
    const id = router.query.id;
    const testFunction = (id) => {
        console.log(id);
    }
    useEffect((id) => {
        testFunction();
    }, [])
    return (
    <div>
    <p>params: {id}</p>
    </div>
  ) 
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

First thing first, you need to name your file with the name of your parameter, (example: [id].tsx)

example

Note: If you put it inside a folder (like the image), the path will be http://localhost:3000/folder-name/your-param

And then, try this code:

import React from 'react'

id.getInitialProps = ({ query }:any) => {
    const { id } = query
    return { id }
}

export default function id({id}:any) {
    console.log(id); // You can use the query outside the return by calling `id`
    return (
        <div>
            <p>params: {id}</p>
        </div>
    )
}
about 4 years ago · Juan Pablo Isaza Relatório

0

try this

import React, { useState, useEffect } from 'react'
    import { useRouter  } from 'next/router'
    import axios from 'axios';
    
    export default function id () {
        const [ response, setResponse ] = useState("");
        const router = useRouter();
        const id = router.query.id;
        const testFunction = (id) => {
            console.log(id);
        }
        useEffect((id) => {
            testFunction();
        }, [router])
        return (
        <div>
        <p>params: {id}</p>
        </div>
      ) 
    }
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda