I’ve been trying to make a get request with axios, but it doesn’t work because the id const doesn’t load and is marked as undefined. Here is my code:
import Head from 'next/head'
import axios from 'axios'
import React, { useEffect, useState } from 'react'
import { useRouter } from 'next/router'
export default function QuejaID() {
const router = useRouter()
const id = router.query.id
console.log(id)
const [queja, setQueja] = useState();
useEffect(() => {
async function request() {
await axios.get(
`http://localhost:3000/quejas/${id}`
).then((response) => {
setQueja(response.data)
console.log(response)
}).catch(err => { console.log(err) })
}
request()
}, []);
return (
<>
<Head>
<title>Quejas</title>
<meta name="description" content="queja" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" href="/favicon.ico" />
</Head>
<main>
{queja ? <div className="container d-flex justify-content-center">
<div className="card text-center w-75 m-5">
<div className="card-header">{queja._id}</div>
<div className="card-body">
<h5 className="card-title">{queja.queja}</h5>
</div>
<div className="card-footer text-muted">{queja.createdAt}</div>
</div>
</div> : <div>No hay ninguna queja con ese ID</div>}
</main>
</>
)
}
So I tried with that and I get an error with axios because it’s undefined.
2
Answers
add
id
to the dependency arrayI think the problem is with the hook
useRouter
. Since you are not using Server-Side Rendering, the objectrouter.query
will be an empty Object hence whyrouter.query.id
is undefined.I suggest you pass the id using serversideprops :