0

I have a component which receives a list of items through props.

It looks like this:

const component = (props) => {
  return (
      <ul>
        {props.list.map((item) => (
          <ListItem key={item.Id} title={item.title} imgSrc={item.img.url} />
        ))}
      </ul>
  );
};

edit: and the child looks like this:

const ListItem = (props) => {
  return (
    <li key={props.key}>
      <h4>{props.title}</h4>
      <div>
        <img src={props.imgSrc} alt='thumbnail'
        />
      </div>
    </li>
  );
};

The list comes from an API and there are cases in which the values I am assigning will be undefined or not available (imgSrc for example). This breaks the entire rendering of the app.

How can I handle errors in a way that will skip the problematic item and continue with the mapping? It usually means this is a deleted item so I wish to skip it all together.

I usually wrap the code with a try-catch or if statement but I am not allowed to do it here.

2 Answers 2

4

There are many options to solve that. For example, you could use the filter method before your .map call.

const component = (props) => {
  return (
      <ul>
        {props.list.filter((item) => item.img.url !== undefined).map((item) => (
          <ListItem key={item.Id} title={item.title} imgSrc={item.img.url} />
        ))}
      </ul>
  );
};

Another possible option could be Error Boundaries. I don't think that they are what you need, but it could be interesting for you anyways.

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

Comments

0

You can conditional rendering.

Array.isArray(props.list) &&
    props.list.map((item) => (
        <ListItem key={item.Id} title={item.title} imgSrc={item.img.url} />
    ));

You can only map over the array if it is an array as:

const component = (props) => {
  return (
      <ul>
        {Array.isArray(props.list) && props.list.map((item) => (
          <ListItem key={item.Id} title={item.title} imgSrc={item.img.url} />
        ))}
      </ul>
  );
};

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.