javascriptasync-awaitbackendfetch-apithemoviedb-api

TypeError: Failed to execute 'fetch' on 'Window': 1 argument required, but only 0 present


I'm doing an API tutorial and I'm catching unexpected error executing async function.

Here's the code:

const tmdbKey = 'here goes my API key';
const tmdbBaseUrl = 'https://api.themoviedb.org/3';
const playBtn = document.getElementById('playBtn');

const getGenres = async () => {
  const genreRequestEndpoint = '/genre/movie/list';
  const requestParams = `?api_key=${tmdbKey}`;
  const urlToFetch = `${tmdbBaseUrl}${genreRequestEndpoint}${requestParams}`;
  try {
    const response = await fetch();
    if (response.ok) {
    const jsonResponse = await response.json();
    console.log(jsonResponse);
    }
  }
  catch(error) {
    console.log(error);
  }
};

After executing getGenres(),

It's expected the try block to log an object to the console, with a single key: genres, instead, the catch block is logging:

TypeError: Failed to execute 'fetch' on 'Window': 1 argument required, but only 0 present.
at getGenres (<anonymous>:10:28)
at <anonymous>:1:1

What have i done wrong?


Solution

  • Your call to fetch is incorrect , you need to set the required argument which is the endpoint link as first argument :

    const response = await fetch(urlToFetch) 
    

    Also , it is a good habit to set the second argument which is an object that includes the method ( GET , POST ... ) , headers ( api key ... ) ...