DEV Community

loading...

Simple Fetch API wrapper that addresses its annoyances and makes it enjoyable to use

Daniel Marcus
Updated on ・2 min read

Fetch API is an improvement in many ways from xhr (though it is missing upload progress), but it's extremely inconsistent at times and isn't the most enjoyable to use.

FarFetch was created to address these issues. Check it out here: https://github.com/WebsiteBeaver/far-fetch. Here's a simple example to show how much more consistent passing in data to the request is in FarFetch, compared to vanilla JS Fetch API.

Fetch API

// GET
async getPerson() {
  const data = { name: 'Jessica', gender: 'f', age: 25 };

  const queryString = `?${new URLSearchParams(Object.entries(data))}`;

  const response = await fetch(`https://example.com/people${queryString}`, {
    method: 'GET',
  });

  if(response.status !== 200) throw new Error('Server error.');

  return response.json();
}

// POST
async addPerson() {
  const data = { name: 'Jessica', gender: 'f', age: 25 };

  const response = await fetch(`https://example.com/people`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(data),
  });

  if(response.status !== 200) throw new Error('Server error.');

  return response.json();
}

// application/x-www-form-urlencoded
async addPerson() {
  const data = { name: 'Jessica', gender: 'f', age: 25 };

  const response = await fetch(`https://example.com/people`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: new URLSearchParams(Object.entries(data)),
  });

  if(!response.ok) throw new Error('Server error.');

  return response.json();
}

FarFetch

// GET
async getPerson() {
  const { responseJSON } = await ff.get('https://example.com/people', {
    data: { name: 'Jessica', gender: 'f', age: 25 },
  });

  return responseJSON;
}

// POST
async addPerson() {
  const { responseJSON } = await ff.post('https://example.com/people', {
    data: { name: 'Jessica', gender: 'f', age: 25 },
  });

  return responseJSON;
}

// application/x-www-form-urlencoded
async addPerson() {
  const { responseJSON } = await ff.post('https://example.com/people', {
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    data: { name: 'Jessica', gender: 'f', age: 25 },
  });

  return responseJSON;
}

Consistency and readable is one of many nice features of FarFetch, along with like simplified uploading, error handling and before/after hooks.

Discussion (0)