0

I'm trying to get and store an API payload in state but i keep getting this error

Error: Objects are not valid as a React child (found: object with keys {page, results, total_pages, total_results}). If you meant to render a collection of children, use an array instead.

The error appears when I try to store data in state but works fine when it is logged to console. The data schema has been declared as shown thus

export interface TrendingMovieModel{
    page: number;
    results: TrendingMovieResultModel[];
    total_pages: number;
    total_results: number;
}

interface TrendingMovieResultModel{
    video: boolean;
    vote_average: number;
    overview: string;
    release_date: string;
    adult: boolean;
    backdrop_path?: string; 
    id: number;
    genre_ids?: number[]; 
    vote_count: number;
    original_language: string;
    original_title: string;
    poster_path?: string;
    title: string;
    popularity: number; 
    media_type: string;
}

The react code


const Moviflix = () => {
    const [movies, setMovies] = useState<TrendingMovieModel>();

    let movie: [] = [];
  useEffect(() => {    
    fetch(`${baseUrl}trending/all/day?api_key=${API_KEY}`)
    .then(response => response.json())
    .then(data => {
      //console.log(data.page);
      //movie = data.response;
      //console.log(data.results)
      setMovies(data)
    }) 
    .catch(err => console.log(err));
  })

  return (
    <div className="App">
      <header className="App-header">
        <Nav /> 
      </header>
      {movies}

pls how can I successfully store this in state?

1 Answer 1

3

The error isn't related to setting the state, it's related to {movies} in your return statement.

React won't render a plain object. You need to map its values to valid components and render those. For example:

movies.results.map((movie) => 
<div>
  <h1>{movie.title}</h1>
  <p>Released: {movie.release_date}</p>
  <p>{movie.overview}</p>
</div>
);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.