Search code examples
reactjshttp-status-code-404

GET http://image.tmdb.org/t/p/w300undefined 404 (Not Found) in React


I passed the movieId and fetched the Movie in detail.js file. But, I see the "GET http://image.tmdb.org/t/p/w300undefined 404 (Not Found)" error in the console. The picture shows correctly and everything is fine. I wanted to fix this error.

And, I really appreciate it if you advise me on a better code.

My code is:

const [movie, setMovie] = useState({});
  const apiImageAddress = "http://image.tmdb.org/t/p/";
  const movieId = props.match.params.id;

  useEffect(() => {
    window.scroll(0, 0);
    axios
      .get(
        `https://api.themoviedb.org/3/movie/${movieId}?api_key=${API}&language=en-US`
      )
      .then((res) => setMovie(res.data));
  }, [movieId]);

  return (
    <Wrap>
      <section className="midContainer">
        <div className="detailLeft">
          <img
            src={`${apiImageAddress}w300${movie.poster_path}`}
            alt="movie_picture"
          />
          <p className="voteAverage">{movie.vote_average}</p>
        </div>

        <div className="detailRight">
          <h1>
            {movie.original_title} ({movie.status})
          </h1>
          <p>Release_Date:{movie.release_date}</p>
          <p>
            Genres:{` `}
            {movie.genres && movie.genres.map((genre) => genre.name).join(", ")}
          </p>
          <p>
            Overview: <br />
            {movie.overview}
          </p>
        </div>
      </section>
    </Wrap>
  );
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.1/umd/react-dom.production.min.js"></script>


Solution

  • On the initial render, movie is just an empty object so movie.poster_path doesn't exist. Just add a conditional to your img src like:

    <img
      src={movie.poster_path ? `${apiImageAddress}w300${movie.poster_path}` : ''}
      alt="movie_picture"
    />