kentcdodds/ama

Fetch wrapper - handle both json & blob responses.

Opened this issue · 0 comments

Hi Kent!

After reading your fetch wrapper blog, I implemented something similar in my project, something like:

export const fetchWithToken = (url, fetchData) => {
  return getCurrentToken()
    .then(({ token }) =>
      fetch(url, {
        ...fetchData,
        headers: {
          ...(fetchData && fetchData.headers),
          Authorization: `Bearer ${token}`,
        },
      })
    )
    .then(handleFetchErrors)
    .then(res => res.json());
};

Now there's a new requirement to add support for res.blob() for binary requests.
So the solutions I thought about were (roughly in order):

  1. Detect the response type based on response header. (not sure how, any suggestions?)
  2. Add "baseFetchWithToken" method that doesn't parse the response, moving responsibility to the consumer.
  3. Add a response-type argument (or create new fetchBlobWithToken method).
  4. Add try-catch, first trying to parse json response then parse blob response. (sounds awful, right? 😬)

Would be happy to hear your thoughts here :)

Thanks a lot for all you valuable content & teaching!