DEV Community

loading...

Discussion on: Fetch vs. Axios - comparison

Collapse
alirezavalizade profile image
alireza valizade

Would be nice to address the way of adding params to fetch since I had issue with it couple of days ago. This is what I use.

const api = (props) => {
  const { url, params = {}, ...rest } = props;
  const parsedURL = new URL(`${process.env.BASE_URL}${url}`);
  const paramsKeys = Object.keys(params);
  if (paramsKeys.length) {
    paramsKeys.forEach((key) => {
      if (params[key]) {
        parsedURL.searchParams.append(key, params[key]);
      }
    });
  }
  return fetch(parsedURL, {
    ...rest
  }).then((res) => res.json());
};

export default api;
Enter fullscreen mode Exit fullscreen mode