Reputation: 25
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
Upvotes: 1
Views: 558
Reputation: 25
Aparently i should have imported from the file axios './axios' not the library 'axios'. Thanks for the help!
Upvotes: 1
Reputation: 157
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()
Upvotes: 0
Reputation: 28380
You should handle your error like this:
const [error, setError] = useState(null);
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);
}
if (error) {
return <div class="error">There was an error loading movies: {err}</div>
}
return <header...</header>
Upvotes: 1