Modified Fetch in project

  • Simple to understand and reusable fetcher method

  • In all projects, where I fetch with the rest API, I use the in-built fetch method all the time. I always avoid third-party libraries like axios.

  • fetch takes two parameters. I will add basic used parameters here. For more info read fetch() - MDN

    
      let url = 'http://localhost:3000/users';
      url = 'http://www.google.com';
      const options = {
          method: 'GET', // 'PUT' | 'POST' | 'DELETE'
          headers: {
              'Content-type': 'application/json'
          },
          body: JSON.stringify({ name: 'name', age: 20 })
      }
      const response = await fetch(url: string, options)
      const data = await response.json()
      // use async await or .then()
    
  • So, for every request(GET, POST, PUT, DELETE), I have to write the above boilerplate again and again for every request.

  • This boilerplate contains, authentication, method names, and body conversion with JSON.stringify(), convert the reponse with response.json() , handle the errors.

  • So I made a simple-to-understand and reusable fetcher method.

  • You should change the below code to meet your requirement.

  • And this is the code:-

export const fetcher = <T>(
  url: string,
  method: "GET" | "PUT" | "POST" = "GET",
  body?: unknown
): Promise<T> => {
  return new Promise(async (resolve, reject) => {
    const options = {
      method,
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(body),
    };
    try {
      const response = await fetch(url, options);
      resolve(response.json());
    } catch (error) {
      reject(error);
    }
  });
};