skip to Main Content

I am trying to access nested JSON objects such as the code below, which works currently.

<img id="inactive-drive2" src='/src/assets/image/InActiveDrive.png' className={info.data.drives[1]?.isActive ? "d-none" : ""} />

If I change my code to this :

<img id="inactive-drive2" src='/src/assets/image/InActiveDrive.png' className={info.data.drives[1].isActive ? "d-none" : ""} />   

get me an error that isActive field is not defined.

I think info.data.drives[1].isActive is correct but when running the app gets an error.

Why does it work this way?

2

Answers


  1. info.data.drives[1] might be undefined at some point when the component renders. If info.data.drives[1] is undefined, trying to access .isActive directly without checking if drives[1] exists first will result in an error. This is why the optional chaining operator ?. is useful – it safely checks if the value exists before attempting to access a property.

    Login or Signup to reply.
  2. The reason why removing the optional operator raises an Error should not be that hard to spot.

    TypeScript does not know in advance if an arbitrary List | Array (eg: info.data.drives) is empty or not – or even defined. There is really no guarantee that it could not potentially be [ ] or even undefined.

    And yet, we are still confident enough to ask it to extract a value from a List, which may or may not even contain anything?🤔 Actually TypeScript is helping out by throwing an Error to indicate that the array might be empty or even undefined or rather Nullish.

    Since there is no complex computation required in this particular Code, you may also move it to a One-Liner Function – "if seeing those Question Marks (?) that annoys You". Something along these Lines:

    const imgClass = (info: InfoType): string => (
        info?.data?.drives[1]?.isActive ? 'd-none' : ''
    ); // even add the optional (?) to others if unsure too
    

    And then use it like so:

    <img id="inactive-drive2" 
         src='/src/assets/image/InActiveDrive.png' 
         className={imgClass(info)} />  
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search