skip to Main Content

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


  1. Chosen as BEST ANSWER

    Here is what I did to set my state with the data received from the API request.

    const[movie, setMovie] = useState({
        ImgPath: '',
        Title: '',
        ReleaseDate: '',
        Rating: '',
        Description: ''
      });
    
    
      useEffect(()=>{
       const baseURL = `https://api.themoviedb.org/3/movie/${id}?api_key=${API_KEY}`;
            axios.get(baseURL)
            .then(res => {
              console.log(res.data);
              let movieData = res.data;
              setMovie({
                ImgPath: movieData.poster_path,
                Title: movieData.title,
                ReleaseDate: movieData.release_date,
                Rating: movieData.vote_average.toString(),
                Description: movieData.overview
              })
            })
            .catch(err => console.error(err))
      }, []);


  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search