const [MovieList, setMovieList] = useState([]);
const options = {
method: 'GET',
headers: {
accept: 'application/json',
Authorization: 'placeholder' // actual token redacted
}
};
useEffect(() => {
const TrendingMovies = async () => {
fetch('https://api.themoviedb.org/3/trending/movie/day?language=en-US', options)
.then(response => response.json())
.then(data => { setMovieList(data.results.slice(0, 1)) })
}
const MovieDetail = async () => {
await fetch(`https://api.themoviedb.org/3/movie/${MovieList[0].id}?language=en-US`, options)
.then(response => response.json())
.then(response => console.log(response))
.catch(err => console.error(err));
}
TrendingMovies();
MovieDetail();
}, [])
There is trendingMovie form where I am getting a detail about a movie and there is an id in that API too so I want to use that id in second API call which is MovieDetail
but it says:
typeError can not read id of undefined.
Can anyone help me with this?
2
Answers
You can use
then
and chain them together.The second function only runs once the first one is resolved.
In general, you could use
await
as well but that is not recommended insideuseEffect
.Alternatively, you can return the value from the 1st function and get it as a parameter in the 2nd function.
Be mindful of error handling. If the first function fails it will not return an ID and the second fn will have
undefined
as a parameter instead which will result also in a failure.Instead of using the two functions you can use one function for api call use async await keyword for data fetching. By this way u can use one api’s data to another api.
also take the setMovieList in the useEffect’s dependency array.