Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using axios in Vue.js with separate service?

I wanted to move axios request logic to separate service in my Vue.js app. Axios always returns promise, how can I fetch response data from it in my component? Or may be there are some other solution for this?

UserService.js

class UserService {
    getUser() {
        const token = localStorage.getItem('token');
        return axios.get('/api/user', {
            headers: {
                'Authorization': 'Bearer ' + token
            }
        }).then(function (response) {
            return response.data;
        }).catch(function (error) {
            console.log(error);
        });
    }
    getUserTasks() {
        const token = localStorage.getItem('token');
        return axios.get('/api/user/task', {
            headers: {
                'Authorization': 'Bearer ' + token
            }
        }).then(response => {
            return response;
        }).catch(function (error) {
            console.log(error);
        });
    }
    get currentUser() {
        return this.getUser();
    }
}
export default new UserService();
like image 388
Nick Synev Avatar asked Jan 27 '18 13:01

Nick Synev


People also ask

Does Axios work with Vue?

js Axios. Vue. js Axios is defined as an HTTP client request for the node and the browser. Axios can be done with simple JavaScript or React and Vue.

Can Axios be used server-side?

One of the important capabilities of Axios is its isomorphic nature which means it can run in the browser as well as in server-side Node. js applications with the same codebase. Axios is also a promise-based HTTP client that can be used in plain JavaScript as well as in advanced JavaScript frameworks like React, Vue.


1 Answers

You can return the promise from the request module and use it anywhere. For example,

sendGet(url) {
    const token = localStorage.getItem('token');
    return axios.get(url, {
        headers: {
            'Authorization': 'Bearer ' + token
        }
    })
}

Since we are not calling .then on the axios result, the promise will not be resolved. Instead, the promise itself will be returned from this method. Thus it can be used as follows,

getUser() {
  axiosWrapper.sendGet('/api/user')
    .then((response)=> {
        // handle response
    })
    .catch((err)=>{
        // handle error
    })
}

However, if you are using a state management solution like vuex or redux, you can combine async actions with the state manager for better control. If you are using redux, you can use redux thunk or redux-saga helper libraries. If you are using vuex, you can handle such side effects in the actions (see here https://vuex.vuejs.org/en/actions.html)

like image 199
Pubudu Dodangoda Avatar answered Oct 18 '22 21:10

Pubudu Dodangoda