Home > Back-end >  How to assign dict value - "TypeError: Cannot read properties of undefined (reading '0
How to assign dict value - "TypeError: Cannot read properties of undefined (reading '0

Time:03-16

UserData from token comes in below format:

name:"TestUser1"
preferrred_username:"Test1"
ver:"2.0"
role: "modify"

For certain users, token does not return 'role' - like below (I want to assign role for these users as "read" thru code) :

name:"TestUser2"
preferrred_username:"Test2"
ver:"2.0"

When I use below code in my component, I am able to get 'role' value as "modify" for first user.

let userRole = this.props.user.account.idTokenClaims.role
disabled={(userRole == "modify") ? false : true} //I disable fields based on user role.

For second user, it throws error saying "TypeError: Cannot read properties of undefined (reading '0')". I understand it returns error as there is no role for second user. How can I handle that error.

If role returns empty string, I can check and assign userRole as "read".

if (this.props.user.account.idTokenClaims.role == "")
{
    let userRole == "read"
}

But token does not return 'role' claim itself. Any suggestion on how to handle this and assign userRole as "read". Thank you

CodePudding user response:

const userRole = this.props.user.account.idTokenClaims?.role || ‘read’

This must do the trick. Now userRole will have a value when you get one from token. And if its not coming in token it’ll default back to ‘read’

If your role is a list, you may try out this

const data = {role: ['read', 'bla','bla','bla']} 
const result = data?.role.find(item => item.toLowerCase() === 'modify') || 'read'
console.log(result)

  • Related