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?

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

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 stackoverflow.com/questions/316781/… for a way that doesn’t rely on url.searchParams.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.