I have to get data from an API using a URL. The problem is I need to get a particular piece of data when the page loads and concatenate to my URL. Then I will fetch data using the URL.
var genre_id;
var genre;
const MOVIE_URL = `https://api.themoviedb.org/3/discover/movie?${API_KEY}&with_genres=${genre_id}`
I will get that particular piece of data using the useNavigate hook (which can only be called in the main functional component).
This is the asynchronous function that will fetch the data using the URL:
async function getMovieImg(url) {
let response = await fetch(url);
let res = response.json()
res.then(data => {
for (var i = 0; i < data.results.length; i++) {
ratings.push(data.results[i].vote_average);
}
})
And this is the main functional component:
function MovieDetails() {
const location = useLocation();
genre_id = location.state.id; {/* This is the piece of data i want in my url*/}
return (
<div>
<p>{ratings}</p>
</div>
)
}
So to recap, I have a URL. I need to get the id of the page (a particular piece of data) and add it to my URL. I can do that using useNavigate hook. However, that hook is called only in the main functional component. And I will fetch data using an asycn function. So basically, async function will run after the main functional component(moviedetails()). Therefore, the data that I will get from the async function will be nothing and thus, I am not able to display that data in the main functional component.
Any help would be appreciated. I need to get the id of page using a hook and at the same time, run an async function.