1

I have this working fine with get.JSON but when I try and use the fetch API instead, it gives me the error "Required parameter: part".

export const fetchYoutube = () => {
  return dispatch => {
    fetchAsync()
    .then(data => console.log(data))
    .catch(reason => console.log(reason.message))

    dispatch({
      type: INCREMENT
    })
  }
}
async function fetchAsync () {
  var query = {
        part: 'snippet',
        key: 'AIzaSyA3IHL73MF00WFjgxdwzg57nI1CwW4dybQ',
        maxResults: 6,
        type: 'video',
        q: 'music'
    }
  let response = await fetch('https://www.googleapis.com/youtube/v3/search', {
    data : query,
    method: 'GET'
  });
  let data = await response.json();
  return data;
}

How do I pass the query object using the fetch API?

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Luiz Almeida
  • 81
  • 1
  • 7

1 Answers1

1

Try attaching the query as params:

replace:

let response = await fetch('https://www.googleapis.com/youtube/v3/search', {
  data : query,
  method: 'GET'
});

with:

var url = new URL("https://www.googleapis.com/youtube/v3/search"),
    query = {
        part: 'snippet',
        key: '#####################################',
        maxResults: 6,
        type: 'video',
        q: 'music'
    }
    Object.keys(query).forEach(key => url.searchParams.append(key, query[key]))

let response = await fetch(url)

Setting query string using Fetch GET request

Squirrl
  • 4,909
  • 9
  • 47
  • 85
  • 1
    This is the correct answer, since the fetch API by design has no built-in convenience mechanism for taking a params object and adding a query string from that to the request. But note also, if you don’t want to rely on url.searchParams (which is supported in current versions of all major browsers but not in Edge before Edge 17 and not in IE at all), then see https://stackoverflow.com/questions/316781/how-to-build-query-string-with-javascript/34209399#34209399 for a way that doesn’t rely on url.searchParams. – sideshowbarker Jan 17 '18 at 22:26