JSFiddle - React, Tailwind, and code Playground

by joplomacedo

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.1/axios.min.js"></script>

JavaScript

const backendConnector = {
    _statusChangeCb: () => {},

    status: 'offline',

    axiosInstance: axios.create({
        baseURL: 'http://localhost:3000',
        timeout: 1000,
    }),

    ping() {
        return this.axiosInstance.get('/ping');
    },

    onStatusChange( cb ) {
        this._statusChangeCb = cb;
    }
};




backendConnector.axiosInstance.interceptors.response.use(function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
  	backendConnector.status = 'online';
    return response;
}, function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    // if offline
    backendConnector.status = 'offline';
    backendConnector._statusChangeCb(status);
    return Promise.reject(error);
});

backendConnector.ping()
	.then( () => console.log(backendConnector.status))
  .catch( () => console.log(backendConnector.status));