rumon
rumon

Reputation: 606

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

Upvotes: 0

Views: 45

Answers (2)

Olivier Boiss&#233;
Olivier Boiss&#233;

Reputation: 18113

you must replace .then((res) => setMovie(res.results)) by .then((res) => setMovie(res)) because the object from the response api doesn't have a results property.

By the way you should remove the movie property from the array passed to the useEffect otherwise you will fetch de data infinitely*

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

Upvotes: 1

Ron Rofe
Ron Rofe

Reputation: 796

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

.then((body) => setMovie(body))

Upvotes: 1

Related Questions