Home > database >  How can I get a data from API promise?
How can I get a data from API promise?

Time:02-08

So I created a separate file for API calls, and my API function looks like this:

const API_BASE = 'https://api.themoviedb.org/3/';
const TMDB_API_KEY = '{api_key}';

export async function fetchPopularMovies() {
      let url: string = `${API_BASE}movie/popular?api_key=${TMDB_API_KEY}`;
      const response = await axios.get(url);
      return response.data;
}

As I guessed, the function returns a promise, so I want to get a data from it. I made a useEffect like this:

const [movies, setMovies] = useState<IMovie[]>();

  useEffect(() =>{
      const response = fetchPopularMovies();
     setMovies(response);
  }, [])

It should set movies to a response I get from the function, but the function is a promise so I can't do it. And I'm wondering how can I get the data, I made return response.data inside of a function, but it returns a promise, so I'm trying to guess what I could do wrong.

CodePudding user response:

use then

const [movies, setMovies] = useState<IMovie[]>();

  useEffect(() =>{
      fetchPopularMovies().then((response) => {
         setMovies(response);
      });
  }, [])
  •  Tags:  
  • Related