Skip to content
Advertisement

How to assign fetched data to React state

I trying to fetch data of an object (in this example from https://api.themoviedb.org/3/movie/459151?api_key=f13446aa3541ebd88cf65b91f6932c5b) and I’m trying to assign it to state movie. However, when I console it out, it has value undefined (actually, it is consoled out twice, firstly with default values of state and secondly as undefined).

import React, {useState, useEffect} from "react";
import Topbar from '../Header/Topbar';
import noImage from '../../images/no-image-available.png';

const movieApiBaseUrl = "https://api.themoviedb.org/3";

interface Movie {
  id: number;
  title: string;
  vote_average: number;
  overview: string;
  poster_path?: string;
  date: string;
}

const MoviePage = (props: any) => {

  const [movie, setMovie] = useState<Movie>(
    {
      id: 0,
      title: '',
      vote_average: 0,
      overview: '',
      poster_path: noImage,
      date: '', 
    }
  );

  const currentMovieId = window.location.pathname.split('/')[2];

useEffect(() => {
  fetch(
    `${movieApiBaseUrl}/movie/${currentMovieId}?api_key=${process.env.REACT_APP_API_KEY}`
  )
    .then((res) => res.json())
    .then((res) => setMovie(res.results))
    .catch(() => {
        return {};
    });
}, [currentMovieId, movie]);

useEffect(() => {
  // here movie is consoled out as undefined
  console.log("::Movie::", movie);
}, [movie]);

  return (
    <React.Fragment>
        <Topbar></Topbar>
        <div className="">
          MOVIE INFO HERE    
        </div>
    </React.Fragment>
  );
}

export default MoviePage;

How to solve it? Thanks

Advertisement

Answer

As it seems in the API endpoint you provided, there is no result key in the body of the response.

.then((body) => setMovie(body))
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement