0

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?

0

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I checked my data and I am sure that this data exists but when running the app get an error and I am forced to use ?. operator
@hmahdavi the data is not relevant here, the type is.
0

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 your are not so comfortable looking at those Question Marks (?)". 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)} />  

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.