Execute custom functions one after another - Callback logic in Vue.js - vue.js

There is a form which submits some data to an API in my component. Assume that it's method is ProcessLogin(). Inside this function I have written my API calls using axios. With the help of then() I have handled my server response and displayed my toast. All good.
Now as a part of my code clean up, I have decided to move all my axios functions to another api.js file and export functions from there. Here is an example function I have in my api.js file :
function ApiLogin(data) {
const url = `${BASE_URL}/authenticate`;
axios.post(url,data).then(response => {
return response;
}).catch(error => {
return error.response;
});
}
On the other side in my component I have my method defined as below :
methods: {
ProcessLogin() {
var status = ApiLogin(this.data);
console.log(status);
}
}
When executing this, I get undefined on my console. I know why it is happening. Because console.log(status) executes before ApiLogin could process and sends it's response. How to handle this kind of situation.? I know that callback is the rescue here, but I am not really sure about how to integrate it.

If you return the axios call from your ApiLogin function:
function ApiLogin(data) {
const url = `${BASE_URL}/authenticate`
return axios.post(url, data)
}
You could then handle the response in your component using then and console log from there:
methods: {
ProcessLogin() {
ApiLogin(this.data)
.then(res => console.log(res))
.catch(err => console.log(err))
}
}
...or with async/await:
methods: {
ProcessLogin: async function() {
try {
var status = await ApiLogin(this.data)
console.log(status)
}
catch(err) {
console.log(err)
}
}
}

Related

Calling methods inside beforeRouteEnter NProgress

I am trying to call an API before navigating to the route. The problem is that if I try to call axios call inside beforeRouteEnter it is working fine for example:
{
beforeRouteEnter(routeTo, routeFrom, next) {
NProgress.start()
axios.get('https://jsonplaceholder.typicode.com/posts').then((res) => {
next((vm) => {
vm.data = res.data
})
NProgress.done()
})
},
}
But when I try to call an API from methods it's navigating to the route before resolving an API and also NProgress bar is also completing before resolving a call.
{
beforeRouteEnter(routeTo, routeFrom, next) {
NProgress.start()
next((vm) => {
vm.index()
NProgress.done()
})
},
methods: {
index() {
axios
.get('https://jsonplaceholder.typicode.com/posts')
.then((res) => {
console.log(res.data)
})
.catch((error) => {
console.log(error)
})
},
},
}
Can anyone guide me what may be wrong?
In your first example, you set the progress bar, then you call the API with Axios and with .then you chain a function after the call. This means the function will wait until the promise is resolved or rejected, before continuing. Only when the axios call is finished successfully, the next function is executed in which you set the data and stop the progress bar. You also should use .catch for if the promises rejects.
Now in your second example, you do not use promises in beforeRouteEnter. Which basically means that all lines are executed immediately. So you call vm.index() and without waiting for the axios call to finish the next line, NProgress.done() will be executed. Although there are several ways to solve this my preference is use async/await, which is just a cleaner way to use promisses and chaining.
In your case I think this would work:
beforeRouteEnter(routeTo, routeFrom, next) {
NProgress.start();
await vm.index();
NProgress.done();
next();
});
}
And the method:
methods: {
async index () {
try {
const response = await axios.get('https://jsonplaceholder.typicode.com/posts');
console.log(response);
} catch (error) {
console.log(error);
}
}
}
Since this is only a part of your component I cannot test it, but I think you get the idea.

ASync/Await is not working as expected in router.BeforeEach guard in vue?

this is my router guard :
router.beforeEach(async (to,from,next)=>{
await store.dispatch('GetPermission');
if(to.matched.some(record => record.meta.requireAuth)){
let permissions=store.state.permissions; //getting empty
console.log(permissions);
if(permissions.filter(per => (per.name === 'read_list').length!=0)){
next({
path:'/dashboard/create'
})
}
else{
next()
}
}
// else if(to.matched.some(record => record.meta.requireAuth)){
// if(store.token!=null){
// next({
// path:'/dashboard'
// })
// }
// else{
// next()
// }
// }
else{
next()
}
});
problem is here though i m using await in dispatch method , i m not getting state value of permissions which is initially empty
here is vuex store code :
GetPermission(context){
axios.defaults.headers.common['Authorization']='Bearer ' + context.state.token
axios.get('http://127.0.0.1:8000/api/user').then((response)=>{
console.log(response)
context.commit('Permissions',response.data.permission)
})
//mutation:
Permissions(state,payload){
state.permissions=payload
}
//state
state:{
error:'',
token:localStorage.getItem('token') || null,
permissions:'',
success:'',
isLoggedin:'',
LoggedUser:{}
}
help me to solve it please ??
actions in Vuex are asynchronous. The only way to let the calling function (initiator of action) to know that an action is complete - is by returning a Promise and resolving it later.
Here is an example: myAction returns a Promise, makes a http call and resolves or rejects the Promise later - all asynchronously
actions: {
myAction(context, data) {
return new Promise((resolve, reject) => {
// Do something here... lets say, a http call using vue-resource
this.$http("/api/something").then(response => {
// http success, call the mutator and change something in state
resolve(response); // Let the calling function know that http is done. You may send some data back
}, error => {
// http failed, let the calling function know that action did not work out
reject(error);
})
})
}
}
Now, when your Vue component initiates myAction, it will get this Promise object and can know whether it succeeded or not. Here is some sample code for the Vue component:
export default {
mounted: function() {
// This component just got created. Lets fetch some data here using an action
this.$store.dispatch("myAction").then(response => {
console.log("Got some data, now lets show something in this component")
}, error => {
console.error("Got nothing from server. Prompt user to check internet connection and try again")
})
}
}
Also,you are calling same route when no permission match, in that case it always call your same route and make infinite loop.
Redirect to access denied page if permission denied.

Vue Router beforeRouteEnter API call response not 'working'

I cannot see why the function is not returning its call back correctly.
I have a list of vehicle on one route and then another route to display that vehicles resource.
This is what I have in my Single file component for the single vehicle resource:
export default {
data() {
return {
vehicle: null,
error: null
}
},
created() {
},
beforeRouteEnter(to, from, next) {
function getVehicle(id) {
console.log('called');
return axios.get(`/api/v1/vehicles/${id}`);
}
getVehicle(to.params.id, (err, vehicle) => {
console.log('response');
next(vm => vm.setData(err, vehicle))
});
},
methods: {
setData (err, vehicle) {
if (err) {
this.error = err.toString();
} else {
this.vehicle = vehicle;
}
}
}
}
This issue is that when clicking a vehicle link, the API call is correctly made and returning a valid response but yet the next() method isn't called and the console log for 'response' isn't shown neither but the 'called' one is.
Not sure on the logic behind it, but had to use .then() for my getVehicle response before it would work. So changed to:
getVehicle(to.params.id).then( response => {
next( vm =>
vm.setData(response)
);
});
I'm not sure it will work with a function inside the beforeRouteEnter guard. Instead try call the axios get method like
let data = axios.get('/api/v1/vehicles/${to.params.id})
next(vm.setData(err, data))
This should work

Get item from AsyncStorage in React Native

I have a list of companies in React Native.
When I click on one of those companies I get the url of the API that is used for selected company. Then I store it to AsyncStorage and then I show the login screen. The function is as follows:
selectCompany(data_url, e) {
AsyncStorage.setItem("data_url", JSON.stringify(data_url), () => this.props.login());
}
Then on login page if I click on sign in button I go to the onLogin function, the function is as follows:
onLogin: function() {
fetch(data.url + '/manager/api/v1/obtain-auth-token/', })
.then(function(body) {
return body.json();
}).then(function(json) {
.....
}).catch(function() {
....
});
},
And data.url comes from data.js file, and I try to get url from the data.js file as follows:
let data_url = AsyncStorage.getItem("data_url").then(json => JSON.parse(json));
module.exports = {
url: data_url,
.....
}
But it doesn't work. Any advice?
AsyncStorage is async, therefore data_url will not be defined until it's retrieved what its looking for, you would need to move the fetch into the promise thats returned from the get so it will run it once it's done getting the data. This might be one way you tackle it:
const data_url = () => AsyncStorage.getItem("data_url"); //change this into a function
module.exports = {
url: data_url,
.....
}
now inside your component...
onLogin: function() {
data.url().then((url) => {
fetch(JSON.parse(url) + '/manager/api/v1/obtain-auth-token/', })
.then(function(body) {
return body.json();
}).then(function(json) {
.....
}).catch(function() {
....
});
});
},
AsyncStorage.getItem is a promise and needs to await for response rather than accessing direct and the function calling it should be defined as async. Here is an example to retrieve from AsyncStorage..
export async function getAccessKey(){
let accessToken = await AsyncStorage.getItem(ACCESS_TOKEN);
return accessToken;
}

Promise isn't working in react component when testing component using jest

Good day. I have the following problem:
I have an item editor.
How it works: I push 'Add' button, fill some information, click 'Save' button.
_onSaveClicked function in my react component handles click event and call function from service, which sends params from edit form to server and return promise.
_onSaveClicked implements
.then(response => {
console.log('I\'m in then() block.');
console.log('response', response.data);
})
function and waits for promise result. It works in real situation.
I created fake service and placed it instead of real service.
Service's function contains:
return Promise.resolve({data: 'test response'});
As you can see fake service return resolved promise and .then() block should work immediatly. But .then() block never works.
Jest test:
jest.autoMockOff();
const React = require('react');
const ReactDOM = require('react-dom');
const TestUtils = require('react-addons-test-utils');
const expect = require('expect');
const TestService = require('./service/TestService ').default;
let testService = new TestService ();
describe('TestComponent', () => {
it('correct test component', () => {
//... some initial code here
let saveButton = TestUtils.findRenderedDOMComponentWithClass(editForm, 'btn-primary');
TestUtils.Simulate.click(saveButton);
// here I should see response in my console, but I don't
});
});
React component save function:
_onSaveClicked = (data) => {
this.context.testService.saveData(data)
.then(response => {
console.log('I\'m in then() block.');
console.log('response', response.data);
});
};
Service:
export default class TestService {
saveData = (data) => {
console.log('I\'m in services saveData function');
return Promise.resolve({data: data});
};
}
I see only "I'm in services saveData function" in my console.
How to make it works? I need to immitate server response.
Thank you for your time.
You can wrap your testing component in another one like:
class ContextInitContainer extends React.Component {
static childContextTypes = {
testService: React.PropTypes.object
};
getChildContext = () => {
return {
testService: {
saveData: (data) => {
return {
then: function(callback) {
return callback({
// here should be your response body object
})
}
}
}
}
};
};
render() {
return this.props.children;
}
}
then:
<ContextInitContainer>
<YourTestingComponent />
</ContextInitContainer>
So your promise will be executed immediately.