1

I am currently practicing React, and my goal is to build a simple app that searches movies and display some short info about them as results. I managed to pull data from API and store em in React hooks. I can access any data, but when I try to pull images I get error:

TypeError: Cannot read property 'medium' of null.

Here are the API results: http://api.tvmaze.com/search/shows?q=$girls

I find an image that I want to use stored in {show.image.medium}

Here is my React code:

import React, {useState, useEffect} from 'react';
import Movie from './Movie';

const App = () => {

const [movies, setMovies] = useState([]);

useEffect(() => {
  getMovies();
}, []);

const getMovies = async () => {
  const response = await fetch(`http://api.tvmaze.com/search/shows?q=$girls`);
  const data = await response.json();
  setMovies(data);
  console.log(data)

  ;}
  return (
    <div>
    <form className='search-form'>
    <input type='text' className='search-bar' placeholder='search movie'>
    </input>
    <button type='submit' className='search-button'>
    Search
    </button>
    </form>
    {movies.map(movie => (
      <Movie title={movie.show.name} image={movie.show.image.medium} />
    ))}
    </div>
  );
};



export default App;

and Movie.js file:

import React from 'react';

const Movie = ({title, image}) => {
    return(
        <div>
        <h1>{title}</h1>
        <img src={image} alt=''/>
        </div>
    );
}

export default Movie;

so I basically mapped the results in movie array, but {movie.show.image.medium} just won't work, while pulling any other data work just fine.

I know that this is probably an easy fix, but I tried everything and searched for an answer for hours and still, nothing worked. I would really appreciate it if someone can explain to me what I am doing wrong. Thanks in advance!

1
  • Are you sure that every movie has an image field ? Commented Jan 5, 2020 at 13:43

1 Answer 1

2

In the API call there is one value where movie.show.image is technically null. For null you could not get any properties, even medium.

What you can do as a solution is the following:

{
   movies.map(movie =>
              movie.show.image ?
                  <Movie title={movie.show.name} image={movie.show.image.medium} /> :
              null)
}

Additionally you need to return from Array.prototype.map().

Iteration from the API on my console:

sceenshot

I hope that helps!

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.