简体   繁体   中英

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?

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';
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM