I am trying to set data received from a GET request from an API using axios. But the value which is getting set is undefined
even though console.log
gives me the correct output.
const[movie, setMovie] = useState({});
useEffect(()=>{
const baseURL = `https://api.themoviedb.org/3/movie/${id}?api_key=${API_KEY}`;
async function getData(){
try{
const response = await axios.get(baseURL);
console.log(response.data); //returns correct value
setMovie(response.data); //sets undefined to the state movie
}
catch(error){
console.error(error);
}
}
getData();
console.log(movie);//logs undefined
},[]);
The API request returns an object when tested in POSTMAN as well as console.log()
, but I am not able set that to the state.
2
Answers
Here is what I did to set my state with the data received from the API request.
In this scenario setMovie is asynchronous, So the console.log will return the value before the updates. In your case, it will return undefined. This is because the component is not re-rendering.
More info here