Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to fix error Object is possibly undefined while accessing data from a map with key value pair?

I have a below list:

const userRolesMap = new Map([
["admin", ["user#1", "user#2"]],
["customer", ["user#3", "user#4"]],
["accounting", ["user#5", "user#6"]]
]);

And, wanted to display these users in user drop down, depending upon user role type.

Now, while rendering it like below, is giving me error Object is possibly 'undefined':

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{!(userRolesMap !== undefined && userRolesMap.size > 0) ? null :
  userRolesMap.get("admin").map((user, index) => (
  <option key={index} value={user}>{user}</option>
))}

Also, tried Object.entries approach but that is also not resolving this error. What am I missing in my approach?

>Solution :

I might be wrong, or you pasted your code wrong, but it looks like you have a typo. You’re using userRoleMap instead of userRolesMap (missing the s). It also looks like you’re using TS so you can use the optional chaining operator.

{!(userRolesMap !== undefined && userRolesMap.size > 0) ? null :
  userRolesMap.get("admin")?.map((user, index) => (
  <option key={index} value={user}>{user}</option>
))}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading