DEV Community

Discussion on: Which functions/methods do you...

Collapse
 
joelbonetr profile image
JoelBonetR 🥇

This will work just for GET requests without authentication, let me do a little tweak on it by just adding an optional "options" parameter 😁

services/api/utils.js

const requestBuilder = (path, options) => fetch(path, options).then(response => response.json()).catch(error => error)
Enter fullscreen mode Exit fullscreen mode

now you can perform any HTTP verb request on a new layer of functions like

PUT example (POST will look mostly the same):
services/api/users.js:

const updateUser = (user) => requestBuilder( Process.env.API_URL, {  
  method: 'PUT',
  body: JSON.stringify(user),
  headers: {
    'Content-Type': 'application/json',
    Authorization: getToken(),
  },
}).then( result => result);
Enter fullscreen mode Exit fullscreen mode

Working example

You can try it in your browser terminal right now:

services/api/pokemon.js:

const getPokemonByName = (pokemon) =>requestBuilder(`https://pokeapi.co/api/v2/pokemon/${pokemon}`, { method: 'GET' })
Enter fullscreen mode Exit fullscreen mode

usage:

getPokemonByName('ditto')
Enter fullscreen mode Exit fullscreen mode