0

I'm retrieving data from an API using fetch which I'm storing within the variable 'data'

This is then being mapped to 'character' which I'm adding to my react component

</Typography>
    <Grid container spacing={3}>
      {data.map((character) => (
        <Grid item xs={12} sm={4} key={character.id}>
          <Card className={classes.card}>
            <CardMedia
              className={classes.media}
              image={character.image_preview_url}
            />

            <CardContent>
              <Typography color="primary" variant="h5">
                {character.name}
              </Typography>

              <Typography color="textSecondary" variant="subtitle2">
              {character.owner.user.username}
              </Typography>

I'm getting the issue on line {character.owner.user.username} because not every record in the returned data will contain a value for this item. How can I set the default to show as "No User" for when the value is returned as NULL ?

2 Answers 2

2

You can use ternary operator.

It's something like this:

<Typography color="textSecondary" variant="subtitle2">
  { character.owner.user.username ? character.owner.user.username : 'No User'}
</Typography>
Sign up to request clarification or add additional context in comments.

Comments

1

you could write something like this:

{character.owner.user.username ? character.owner.user.username : "No user"}

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.