Const variable outside function Javascript

I have multi exported function to handle API request. I stuck with some problem.

Please read my code here:

export const CreateAPI = (path, dataForm) => {
  const loading = document.querySelector('.loading-bar');
  loading.classList.add('is-loading');

  return Axios.post(`${process.env.REACT_APP_API_SERVER}${path}`, dataForm, {
    headers: { 'Content-Type': 'multipart/form-data' }
  })
    .then(res => {
      if (res.status >= 200 && res.status <= 299) {
        loading.classList.remove('is-loading');
        return res.status
      } else {
        Promise.reject(res);
      }
    })
    .catch(err => console.log(err));
}

export const ReadAPI = (path, params) => {
  const loading = document.querySelector('.loading-bar');
  loading.classList.add('is-loading');

  return Axios.get(`${process.env.REACT_APP_API_SERVER}${path}${params || ''}`)
    .then(res => {
      if (res.status >= 200 && res.status <= 299) {
        loading.classList.remove('is-loading');
        return res.data
      } else {
        Promise.reject(res);
      }
    })
    .catch(() => {
      localStorage.removeItem('jwtToken');
      window.location.href = './login';
    });
}

How to make const loading reusable for any exported function?

Answer

Something like this? BTW, you could extract the loading service to a separate file.

Simple fiddle to demonstrate the idea.

https://jsfiddle.net/ramseyfeng/hpaLn9kj/10/

const loading = document.querySelector('.loading-bar');
loading.start = () => {
  loading.classList.add('is-loading');
};

loading.stop = () => {
  loading.classList.remove('is-loading');
};

export const CreateAPI = (path, dataForm) => {
  loading.start();
  return Axios.post(`${process.env.REACT_APP_API_SERVER}${path}`, dataForm, {
    headers: { 'Content-Type': 'multipart/form-data' }
  })
    .then(res => {
      if (res.status >= 200 && res.status <= 299) {
        loading.stop();
        return res.status
      } else {
        Promise.reject(res);
      }
    })
    .catch(err => console.log(err));
}

export const ReadAPI = (path, params) => {
  loading.start();
  return Axios.get(`${process.env.REACT_APP_API_SERVER}${path}${params || ''}`)
    .then(res => {
      if (res.status >= 200 && res.status <= 299) {
        loading.stop();
        return res.data
      } else {
        Promise.reject(res);
      }
    })
    .catch(() => {
      localStorage.removeItem('jwtToken');
      window.location.href = './login';
    });
}
Source: stackoverflow
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .