In my project, I am setting an object in local storage. It is set perfectly and it can be accessed from any other page. But when I try to access the object from local storage in index.js file it sometimes returns the values of the object but maximum time returns null. why such happens?
This is how I set object in local storage
if(response.body.role === '1'){
authUser.id = response.body.id
authUser.email = response.body.email
authUser.role = 1
window.localStorage.setItem('authUser', JSON.stringify(authUser));
self.$router.push({path: 'admin'});
}
here authUser is an object declared before.
This is how I am accessing the authUser object in index.js file
const authUser = JSON.parse(window.localStorage.getItem('authUser'))
`
var roleshash = {
1: 'admin',
2: 'doctor',
3: 'receptionist',
4: 'patient'
}
`
{
path: '/admin', //sidebar
component: Sidebar,
beforeEnter: (to, from, next) => {
if (authUser.role === 1) {
next();
}
else {
Swal.fire({
type: 'error',
title: 'Access Denied!',
text: 'Unauthorized access occured'
})
next({ path: '/' + roleshash[authUser.role] })
}
}
}
But it shows Uncaught (in promise) TypeError: Cannot read property 'role' of null
I don't know why such a happening. Can anybody help?