Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

react.js error handling inside functional component

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading