I am getting the below error
AxiosError {message: 'Request failed with status code 404
The code is:
"use client"
import axios from "axios";
import { useEffect, useState } from "react";
const page = ({params}) => {
const [paramsObj, setparamsObj] = useState({})
const awaitParams = async ()=>{
const awaitedParams = await params;
setparamsObj(awaitedParams);
}
useEffect(() => {
awaitParams();
}, [])
const {id}= paramsObj;
console.log(id);
const getUser=async ()=>{
const response= await axios.get(`/${id}`);
console.log(response.data);
}
useEffect(() => {
getUser();
},[] )
return (
<div>page{id}</div>
)
}
export default page
I was expecting to get the user object corresponding to the id on my console, but it is showing the error. Though I replace the ${id} with any value like 1, then it gives the user object with id 1 on console. I am stuck and not getting answer anywhere.
I am getting the below error
AxiosError {message: 'Request failed with status code 404
The code is:
"use client"
import axios from "axios";
import { useEffect, useState } from "react";
const page = ({params}) => {
const [paramsObj, setparamsObj] = useState({})
const awaitParams = async ()=>{
const awaitedParams = await params;
setparamsObj(awaitedParams);
}
useEffect(() => {
awaitParams();
}, [])
const {id}= paramsObj;
console.log(id);
const getUser=async ()=>{
const response= await axios.get(`https://jsonplaceholder.typicode.com/users/${id}`);
console.log(response.data);
}
useEffect(() => {
getUser();
},[] )
return (
<div>page{id}</div>
)
}
export default page
I was expecting to get the user object corresponding to the id on my console, but it is showing the error. Though I replace the ${id} with any value like 1, then it gives the user object with id 1 on console. I am stuck and not getting answer anywhere.
The reason of error is that id
is undefined at first. and because of that u face the error and no result.
First of all
u don't need to use useEffect
& useState
to get the query search params in page component in nextjs. instead of :
const page = ({params}) => {
const [paramsObj, setparamsObj] = useState({})
const awaitParams = async ()=>{
const awaitedParams = await params;
setparamsObj(awaitedParams);
}
useEffect(() => {
awaitParams();
}, [])
Do this :
const page = ({params}) => {
const awaitedParams = await params;
And then, move your fetch
function, into useEffect , like this :
useEffect(() => {
if (!id) return;
const getUser = async () => {
try {
const response = await axios.get(`https://jsonplaceholder.typicode.com/users/${id}`);
console.log(response.data);
} catch (error) {
console.error("Error fetching user:", error);
}
};
getUser();
}, [id]);
. It should work.