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.
id in the function.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>
)
}
First thing first, you need to name your file with the name of your parameter, (example: [id].tsx)
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>
)
}
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>
)
}