skip to Main Content
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


  1. You can use then and chain them together.

    TrendingMovies().then(() => MovieDetail());
    

    The second function only runs once the first one is resolved.
    In general, you could use await as well but that is not recommended inside useEffect.

    Alternatively, you can return the value from the 1st function and get it as a parameter in the 2nd function.

    function TrendingMovies(){
      return fetch(...).then((data) => data...id); // Make sure you return id
    }
    
    function MovieDetail(id){
      // Your fetch fn here
    }
    
    // You can invoke them as
    TrendingMovies().then(id => MovieDetail(id));
    

    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.

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search