Home > Net >  uncaught (in promise) axios react
uncaught (in promise) axios react

Time:07-29

I am trying to build a netflix clone and on line 12 from the Banner.js file a get the uncaught (in promise) AxiosError. The thing is that the banner doesn't display at all, 'movies' is empty.

Banner.js:

import axios from 'axios';
import React, { useEffect, useState} from 'react'
import requests from "./requests";

function Banner() {
  const [movie, setMovie] = useState([]);

  useEffect(() => {
    async function fetchData() {
        const request = await axios.get(requests.fetchNetflixOriginals);
        setMovie(
           request.data.results[
              Math.floor(Math.random() * request.data.results.length -1)
            ]
           );
        return request;
    }
    fetchData();
}, []);

console.log(movie);

return (
<header className="banner"
    style={{
        backgroundSize: "cover",
        backgroundImage: `url(
         "https://image.tmdb.org/t/p/original/${movie?.backdrop_path}"
         )`,
        backgroundPosition: "center center"
    }}
>

    <div className="banner__contents">
        <h1>{movie?.title || movie?.name || movie?.original_name}
        </h1>

       
    {/* description */}

    </div>
    
</header>
)
}

 export default Banner

CodePudding user response:

You should handle your error like this:

  1. Create some state for the error:
const [error, setError] = useState(null);
  1. Wrap your request in a try/catch.
    try {
       const request = await axios.get(requests.fetchNetflixOriginals);
       setError(null); // in case it had a value previously
       setMovie(
           request.data.results[
              Math.floor(Math.random() * request.data.results.length -1)
            ]
           );
        return request;
    } catch (err) {
      setError(err);
    }
  1. Render the error if it exists:
if (error) {
    return <div >There was an error loading movies: {err}</div>
}
return <header...</header>

CodePudding user response:

First you have to wrap your codes in try and catch blocks to prevent the error then you get the promise so try this

const data = await request.json()
  • Related