VueRouter wait for ajax is done - javascript

I am building SPA and the problem is checking if user is admin or not.
After Vue.auth.getUserInfo() I want to stop whole application and wait for API response, Vue.auth.user.isAdmin is always false because I don't have response from api...
Here is router.beforeEach
router.beforeEach((to, from, next) => {
if(Vue.auth.user.authenticated == false) {
Vue.auth.getUserInfo();
}
if(Vue.auth.user.isAdmin) {
next({ name: 'admin.index' })
} else {
next({name: 'client.index'})
}
}
Get user info method:
getUserInfo() {
Vue.http.get('/api/me')
.then(({data}) => {
this.user = data;
}, () => {
this.logout();
})
}

Assuming the state of Vue.auth.user.isAdmin is managed within your Vue.auth.getUserInfo() logic, you can try a promise approach (untested):
getUserInfo() {
return new Promise((resolve, reject) => {
Vue.http.get('/api/me')
.then(({data}) => {
this.user = data;
// Or, to use when consuming this within the then() method:
resolve(data);
}, () => {
reject();
})
})
}
Then, when you consume it in your guard (https://router.vuejs.org/en/advanced/navigation-guards.html):
// A couple small auth/guard helper functions
function guardCheck(next) {
if(Vue.auth.user.isAdmin) {
next({ name: 'admin.index' })
} else {
next({name: 'client.index'})
}
}
function guardLogout(next) {
Vue.auth.user.logout()
.then(() => {
next({ name: 'home.index', params: { logout: success }})
})
}
router.beforeEach((to, from, next) => {
if(Vue.auth.user.authenticated === false && !to.matched.some(record => record.meta.isGuest)) {
Vue.auth.getUserInfo()
.then((user) => {
guardCheck(next)
})
.catch(() => {
// Not sure how your logout logic works but maybe...
guardLogout(next)
})
} else {
guardCheck(next)
}
}

It is asynchronus request.
You have few options.
1. Move this function to vue-router and place your code:
if(Vue.auth.user.authenticated == false) {
Vue.auth.getUserInfo();
}
if(Vue.auth.user.isAdmin) {
next({ name: 'admin.index' })
} else {
next({name: 'client.index'})
}
}
in then() function of your request.
Probably better for your learning curve - to modify your getUserInfo() to be promise based.
You will then have in your auth module something like:
var getUserInfo = new Promise((resolve,reject) => {
Vue.http.get('/api/me')
.then(({data}) => {
this.user = data;
resolve();
}, () => {
this.logout()
reject();
})
}
and in your router:
router.beforeEach((to, from, next) => {
if(Vue.auth.user.authenticated == false) {
Vue.auth.getUserInfo().then(()=>{
if(Vue.auth.user.isAdmin) {
next({ name: 'admin.index' })
} else {
next({name: 'client.index'})
}
});
}
}
I don't have an editor with me so it can have some small issues but generally should work. Hope it helps!

Related

TypeError: undefined is not an object (evaluating '_this.props.auth(values.username, values.password).then')

I'm developing a ReactJS app.
I'm getting the following error "TypeError: undefined is not an object (evaluating '_this.props.auth(values.username, values.password).then')".
When the "return new Promise" is outside the "then" it works properly. Nonetheless, I want to return the promise after only the two first "then"s.
Sample of loginActions.js
export const auth = (username, password) => dispatch => {
fetch('http://localhost/webservices/login', {
method: 'post',
body: JSON.stringify({ username, password })
})
.then(res => {
if(res.ok) {
console.log("Succeeded.", res);
return res.json();
} else {
console.log("Failed.", res);
return res.json();
}
})
.then(json => {
if (json.token) {
auth_status.value = true;
return auth_status.value;
} else {
auth_status.value = false;
return auth_status.value;
}
})
.then(function(res){
return new Promise((resolve, reject) => {
dispatch({
type: VERIFY_AUTH,
payload: res
});
resolve();
})
})
.catch(err => {
console.error(err);
});
};
Sample of login.js
handleSubmit = (e) => {
e.preventDefault();
this.props.form.validateFields((err, values) => {
if (!err) {
console.log("Received values of form: ", values);
this.props.auth(values.username, values.password).then(() => {
if (this.props.auth_status === true) {
message.success("Welcome!", 3);
this.setState({
redirect: true
});
} else {
message.error("The username and password combination is incorrect", 3);
}
})
.catch(err => {
console.error(err);
});
}
});
};
Your action auth is not returning anything. The return statements in the asynchronous handlers do not return for the action itself.
You need to return a Promise in your auth() action that you resolve yourself in the third then:
export const auth = (username, password) => dispatch => {
// instantly return a new promise that
// can be resolved/rejected in one of the handlers
return new Promise((resolve, reject) => {
fetch('http://localhost/webservices/login', {
method: 'post',
body: JSON.stringify({
username,
password
})
}).then(res => {
if (res.ok) return res.json();
// your probably also want to reject here
// to handle the failing of the action
reject();
}).then(json => {
if (json.token) {
auth_status.value = true;
return auth_status.value;
} else {
auth_status.value = false;
return auth_status.value;
}
}).then(res => {
dispatch({
type: VERIFY_AUTH,
payload: res
});
// resolve the original promise here
resolve();
}).catch(err => console.error(err));
});
};

Axios ajax, show loading when making ajax request

I'm currently building a vue app and Im using axios. I have a loading icon which i show before making each call and hide after.
Im just wondering if there is a way to do this globally so I dont have to write the show/hide loading icon on every call?
This is the code I have right now:
context.dispatch('loading', true, {root: true});
axios.post(url,data).then((response) => {
// some code
context.dispatch('loading', false, {root: true});
}).catch(function (error) {
// some code
context.dispatch('loading', false, {root: true});color: 'error'});
});
I have seen on the axios docs there are "interceptors" but II dont know if they are at a global level or on each call.
I also saw this post for a jquery solution, not sure how to implement it on vue though:
$('#loading-image').bind('ajaxStart', function(){
$(this).show();
}).bind('ajaxStop', function(){
$(this).hide();
});
I would setup Axios interceptors in the root component's created lifecycle hook (e.g. App.vue):
created() {
axios.interceptors.request.use((config) => {
// trigger 'loading=true' event here
return config;
}, (error) => {
// trigger 'loading=false' event here
return Promise.reject(error);
});
axios.interceptors.response.use((response) => {
// trigger 'loading=false' event here
return response;
}, (error) => {
// trigger 'loading=false' event here
return Promise.reject(error);
});
}
Since you could have multiple concurrent Axios requests, each with different response times, you'd have to track the request count to properly manage the global loading state (increment on each request, decrement when each request resolves, and clear the loading state when count reaches 0):
data() {
return {
refCount: 0,
isLoading: false
}
},
methods: {
setLoading(isLoading) {
if (isLoading) {
this.refCount++;
this.isLoading = true;
} else if (this.refCount > 0) {
this.refCount--;
this.isLoading = (this.refCount > 0);
}
}
}
demo
I think you are on the right path with dispatch event when ajax call start and finish.
The way that I think you can go about it is to intercept the XMLHttpRequest call using axios interceptors like so:
axios.interceptors.request.use(function(config) {
// Do something before request is sent
console.log('Start Ajax Call');
return config;
}, function(error) {
// Do something with request error
console.log('Error');
return Promise.reject(error);
});
axios.interceptors.response.use(function(response) {
// Do something with response data
console.log('Done with Ajax call');
return response;
}, function(error) {
// Do something with response error
console.log('Error fetching the data');
return Promise.reject(error);
});
function getData() {
const url = 'https://jsonplaceholder.typicode.com/posts/1';
axios.get(url).then((data) => console.log('REQUEST DATA'));
}
function failToGetData() {
const url = 'https://bad_url.com';
axios.get(url).then((data) => console.log('REQUEST DATA'));
}
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<button onclick="getData()">Get Data</button>
<button onclick="failToGetData()">Error</button>
For Nuxt with $axios plugin
modules: ['#nuxtjs/axios', ...]
plugins/axios.js
export default ({ app, $axios ,store }) => {
const token = app.$cookies.get("token")
if (token) {
$axios.defaults.headers.common.Authorization = "Token " + token
}
$axios.interceptors.request.use((config) => {
store.commit("SET_DATA", { data:true, id: "loading" });
return config;
}, (error) => {
return Promise.reject(error);
});
$axios.interceptors.response.use((response) => {
store.commit("SET_DATA", { data:false, id: "loading" });
return response;
}, (error) => {
return Promise.reject(error);
})
}
store/index.js
export default {
state: () => ({
loading: false
}),
mutations: {
SET_DATA(state, { id, data }) {
state[id] = data
}
},
actions: {
async nuxtServerInit({ dispatch, commit }, { app, req , redirect }) {
const token = app.$cookies.get("token")
if (token) {
this.$axios.defaults.headers.common.Authorization = "Token " + token
}
let status = await dispatch("authentication/checkUser", { token })
if(!status) redirect('/aut/login')
}
}
}
This example is accompanied by a token check with $axios and store

Redux return promise

I have a simple function to log out (just for testing) and I would like to inform the user when the action is completed. First that came in mind is to do this with promises.
I tried like this but there is something wrong with it. I don't quite understand how these works. Am I able to do it like this or would there be a better approach?
Function
logOut = () => {
this.props.logoutUser().then((passed) => {
if (passed) {
alert("You are now logged out!");
}
});
};
Logout action
export function logoutUser() {
return dispatch => {
new Promise(function (resolve, reject) {
dispatch(logout()).then((response) => {
return true;
}).catch((error) => {
return false;
});
});
}
}
function logout() {
return {
type: "LOGOUT"
}
}
Problem with Logout function
export function logoutUser() {
return dispatch => {
new Promise(function (resolve, reject) {
dispatch(logout()).then((response) => {
resolve(true); // changed
}).catch((error) => {
reject(error); // changed
});
});
}
}
you have to pass callback function resolve for success, and reject for fail.
refer this link
Update : and secondly you have to use thunk middleware, to work dispatch like Promise object : github
you can also do this with callback, like so -
logOut = () => {
this.props.logoutUser(result => {
if (result.success) {
alert("You are now logged out!");
return;
}
// Handle error
});
};
export function logoutUser(callback) {
logout()
.then(() => callback({ success: true }))
.catch(error => callback({ error }));
return dispatch => {
dispatch({
type: "LOGOUT"
});
};
}
function logOut() {
// log out function that returns a promise
}

VueJS: Fetch data before and after loading a component

I am new to VueJS and working on a component and want to fetch some data from an API before the corresponding route is loaded; only then the component should load. Once the component is created, I have to call another API that takes as input the data obtained from first API. Here is my component script:
export default {
name: 'login',
data () {
return {
categories: []
}
},
created () {
// it gives length = 0 but it should have been categories.length
console.log(this.categories.length);
// Call getImage method
loginService.getImage(this.categories.length)
.then(res => {
console.log('Images fetched');
})
},
beforeRouteEnter (to, from, next) {
loginService.getCategories().then((res) => {
next(vm => {
vm.categories = res.data.categories;
});
}, (error) => {
console.log('Error: ', error);
next(error);
})
},
methods: {}
}
I tried using mounted hook but it does not work. However if I watch the categories property and call fetch image method, it works. I don't think using watchers is the best approach here. Any thoughts?
Move your call to get additional information into a method and call that method from next.
export default {
name: 'login',
data () {
return {
categories: []
}
},
beforeRouteEnter (to, from, next) {
loginService.getCategories().then((res) => {
next(vm => {
vm.categories = res.data.categories;
vm.getMoreStuff()
});
}, (error) => {
console.log('Error: ', error);
next(error);
})
},
methods: {
getMoreStuff(){
console.log(this.categories.length);
// Call getImage method
loginService.getImage(this.categories.length)
.then(res => {
console.log('Images fetched');
})
}
}
}
Alternatively, do it in the callback for getCategories.
loginService.getCategories()
.then(res => {
vm.categories = res.data.categories;
loginService.getImage(vm.categories.length)
.then(res => //handle images then call next())
})
.catch(err => //handle err)
Or if you are using a pre-compiler that handles async/await
async beforeRouteEnter(to, from, next){
try{
const categoryResponse = await loginService.getCategories()
const categories = categoryResponse.data.categories
const imageResponse= await loginService.getImage(categories.length)
next(vm => {
vm.categories = categories
vm.images = imageResponse.data.images
})
} catch(err){
//handle err
}
}

ES7 timeout for async/await fetch

I want to set timeout in my fetch method, and I follow this github issue.
from #mislav answer, we could custom timeout method like below.
// Rough implementation. Untested.
function timeout(ms, promise) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
reject(new Error("timeout"))
}, ms)
promise.then(resolve, reject)
})
}
timeout(1000, fetch('/hello')).then(function(response) {
// process response
}).catch(function(error) {
// might be a timeout error
})
and improved by #nodkz
function timeoutPromise(ms, promise) {
return new Promise((resolve, reject) => {
const timeoutId = setTimeout(() => {
reject(new Error("promise timeout"))
}, ms);
promise.then(
(res) => {
clearTimeout(timeoutId);
resolve(res);
},
(err) => {
clearTimeout(timeoutId);
reject(err);
}
);
})
}
but I want to call that method in ES7 async/await syntax, I try below way but failed.
async request() {
try {
let res = await timeout(1000, fetch('/hello'));
} catch(error) {
// might be a timeout error
}
}
and how could I use it in ES7 async/await syntax?
thanks for your time.
update
thanks for #Bergi reply, and I display my code in http request step.
ES7 fetch
'use strict';
import { configApi, } from 'tyrantdb-config';
import { timeoutPromise, } from 'xd-utils-kit';
const keyResponse = configApi.keyResponse;
const KEY_DATA = keyResponse.data;
module.exports = {
async fetchLogin(url, params, dataRely) {
let {
self, processor, route,
storage, isLocalStoraged,
email, password, _warning, } = dataRely;
self.setState({ isWait: true, });
try {
let res = await timeoutPromise(10, fetch(url, params));
if (res.status >= 200 && res.status < 300) {
let resJson = await res.json();
let resData = resJson[KEY_DATA];
let cache = {
...resData,
password,
};
if (isLocalStoraged !== true) {
processor(cache, storage);
}
global.g_user = cache;
self.setState({ isWait: false, });
// clean user info which already bind to self[this]
self.email = self.password = null;
self.isLocalStoraged = false;
route();
} else {
console.log(`[login] response code: ${res.status}`);
self.setState({ isWait: false, });
_warning();
}
} catch(error) {
console.error(error);
}
},
saveLoginState: (cache, storage) => {
storage.save({
key: 'loginState',
rawData: cache,
});
},
openURL: (url, Linking) => {
Linking.canOpenURL(url).then(supported => {
if (!supported) {
console.log(`can\'t handle url: ${url}`);
} else {
return Linking.openURL(url);
}
}).catch((err) => {
console.log(`error occurred: ${err}`);
})
},
};
ES6 fetch
'use strict';
import { configApi, } from 'tyrantdb-config';
import { timeoutPromise, } from 'xd-utils-kit';
const keyResponse = configApi.keyResponse;
const KEY_DATA = keyResponse.data;
module.exports = {
fetchLogin(url, params, dataRely) {
let {
self, processor, route,
storage, isLocalStoraged,
email, password, _warning, } = dataRely;
self.setState({ isWait: true, });
timeoutPromise(1000, fetch(url, params))
.then((res) => {
if (res.status >= 200 && res.status < 300) {
return res.json();
} else {
console.log(`[login] response code: ${res.status}`);
self.setState({ isWait: false, });
_warning();
}
})
.then((resJson) => {
let resData = resJson[KEY_DATA];
let cache = {
...resData,
password,
};
if (isLocalStoraged !== true) {
processor(cache, storage);
}
global.g_user = cache;
self.setState({ isWait: false, });
// clean user info which already bind to self[this]
self.email = self.password = null;
self.isLocalStoraged = false;
route();
})
.catch(error => console.error(error))
.done();
},
saveLoginState: (cache, storage) => {
storage.save({
key: 'loginState',
rawData: cache,
});
},
openURL: (url, Linking) => {
Linking.canOpenURL(url).then(supported => {
if (!supported) {
console.log(`can\'t handle url: ${url}`);
} else {
return Linking.openURL(url);
}
}).catch((err) => {
console.log(`error occurred: ${err}`);
})
},
};
above ES6 fetch will catch output below, I think #Bergi is right, It's my code fault, not timeoutPromise error.
2016-06-08 22:50:59.789 [info][tid:com.facebook.React.JavaScript] [login] response code: 400
2016-06-08 22:50:59.808 [error][tid:com.facebook.React.JavaScript] { [TypeError: undefined is not an object (evaluating 'KEY_DATA')]
line: 103795,
column: 29,
sourceURL: 'http://172.26.129.189:8081/index.ios.bundle?platform=ios&dev=true' }
2016-06-08 22:50:59.810 [error][tid:com.facebook.React.JavaScript] One of the sources for assign has an enumerable key on the prototype chain. This is an edge case that we do not support. This error is a performance optimization and not spec compliant.
2016-06-08 22:50:59.810 [info][tid:com.facebook.React.JavaScript] 'Failed to print error: ', 'One of the sources for assign has an enumerable key on the prototype chain. This is an edge case that we do not support. This error is a performance optimization and not spec compliant.'

Categories

Resources