Seng Foong
Seng Foong

Reputation: 111

CastError: Cast to ObjectId failed for value "undefined" at path

I am trying to use get data from apis, at my useEffect function, it consists of 2 get request. The 2nd get request needed a parameter which is based on the 1st get request's return value. But I encounter a error which is CastError: Cast to ObjectId failed for value "undefined" at path from mongoose. Anyone can help or is there any clean way to solve? Much appreciate!

for example:

 const[data,setdata]=useState([])
 useEffect(() => {
    axios.get('http:localhost.....').then({res=>{
         setdata(res.data)
  }})
   axios.get(`http:localhost.....${data._id}`)
}, [])

Upvotes: 0

Views: 54

Answers (1)

Roy.B
Roy.B

Reputation: 2106

Thats because data will be avalibale at next render, add another useEffect to trigger the second call when data has value:

 const[data, setData]= useState([]);

 useEffect(() => {
    axios.get('http:localhost.....').then(res=> setData(res.data);
  }, [])

useEffect(() => {
   if(data.lenght){
     axios.get(`http:localhost.....${data._id}`);
   }
  }, [data])

Upvotes: 1

Related Questions