0

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

enter image description here

I don't know why such a happening. Can anybody help?

connexo
  • 53,704
  • 14
  • 91
  • 128
Ajmal-Hossain
  • 215
  • 5
  • 19
  • this code is within the same file ? verify the declaration and the scope of your declaration (var, vs let ) etc. – M. Gara Oct 30 '19 at 14:51
  • See updates, please. Basically authUser is set in `Login.vue` but now I'm trying to access it from index.js – Ajmal-Hossain Oct 30 '19 at 15:01
  • Please check if your question is a duplicate of https://stackoverflow.com/questions/9742395/scope-of-sessionstorage-and-localstorage. Both pages, the Login page and the page that wants to read from localStorage, have to be on the same domain and protocol. Regarding your error message, it means that `authUser` doesn't exist in `localStorage` on that page. – connexo Oct 30 '19 at 15:14
  • but suddenly autheUser get value. nost of the time it does not – Ajmal-Hossain Oct 30 '19 at 18:05

0 Answers0