1

When trying to conditionally render something from a datastructure, I want the element to appear if there exists a record of it in the dataset, but not if it doesnt. My attempt for this was this:

// other code...

{patient.address[0]
    ? patient.address[0].line[0]
    : null}

// other code...

This works for instances where the field is present, but when it isnt - i get a " TypeError: Cannot read property '0' of undefined".

I think the problem is that when trying to access .address[0], the error gets thrown due to the array not existing on the dataset, before it can enter the conditional. How can I ammend my approach to fix this?

3 Answers 3

4

You can just use a couple of question marks:

patient?.address?.[0]?.line?.[0];

https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#optional-chaining

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

1 Comment

Thank you! I wasn't aware this was possible, and simplified the task.
1

You can check in different ways

  • Using optional chaining like below, you can explore more about Optional chaining here
{patient?.address?.[0]?.line?.[0] ?? null}
  • By using default values like below
{((patient || {}).address || [])[0]
    ? ((((patient || {}).address || [])[0]).line || [])[0]
    : null}

Simplified version of above

let address = ((patient || {}).address || [])[0]
{ address ? (address.line || [])[0] : null}

6 Comments

You don't need ternary with your first example, since it already defaults to undefined. If you really need null instead (which you don't, it's the same thing in React render), you can simplify it to patient?.address?.[0]?.line?.[0] ?? null
Thank you for your answer Nithish, and thank you for the comment, @ritaj. I was wondering about exactly that, as this is how it reacted in my app.
?? null would be still needed, if you return the value directly in render/ the function body.
No, render can take null, undefined, false or true and it will behave the same
@ritaj No, you cannot directly return undefined in a component, take a look at their API docs. Though something like return <div>{undefined}</div> is possible.
|
0

Use this short circuit approach:

patient?.address?.0?.line && patient.address[0].line[0]

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.