Refactor: Expected to return a value at the end of arrow function

Viewed 79

I have following code:

<DetailsBox title={t('catalogPage.componentDetails.specs.used')}>
  {component?.projects.map(project => {
    projectList?.map(name => {
      if (project.id === name.id) {
        return (
          <Typography variant="body2" gutterBottom classes={{}}>
            {`${name.name}`}
          </Typography>
        );
      }
    });
  })}
</DetailsBox>

and I got Expected to return a value at the end of arrow function, I know that it is caused by return in anonymous function, but how to refactor it?

Edit: The error is assigned to following line: projectList?.map(name => {

3 Answers

The warning is because you're only sometimes returning something from the .map; the resulting array will currently sometimes contain undefined elements interspersed with Typography components.

Use .filter instead, to filter out the IDs that don't match:

<DetailsBox title={t('catalogPage.componentDetails.specs.used')}>
  {component?.projects.map(project => (
    projectList
      ?.filter(name => project.id === name.id)
      ?.map(name => (
          <Typography variant="body2" gutterBottom classes={{}}>
            {`${name.name}`}
          </Typography>
      ))
  ))}
</DetailsBox>

Or, if there happens to be only a single match at most for every pair, it would be more appropriate to create an object or Map of IDs to the projects items or to the projectList items - this will reduce the computational complexity to O(n) from O(n ^ 2).

Your parent function isn't returning a value. So, you either need to use parentheses for an implicit return or an explicit return statement:

Implicit:

<DetailsBox title={t('catalogPage.componentDetails.specs.used')}>
  {component?.projects.map(project => (
    projectList?.map(name => {
      if (project.id === name.id) {
        return (
          <Typography variant="body2" gutterBottom classes={{}}>
            {`${name.name}`}
          </Typography>
        );
      }
    ));
  })}
</DetailsBox>

Explicit return:

<DetailsBox title={t('catalogPage.componentDetails.specs.used')}>
  {component?.projects.map(project => {
    return projectList?.map(name => {
        if (project.id === name.id) {
          return (
            <Typography variant="body2" gutterBottom classes={{}}>
              {`${name.name}`}
            </Typography>
          );
        }
    })
  })}
</DetailsBox>

Try

<DetailsBox title={t('catalogPage.componentDetails.specs.used')}>
  {component?.projects.map(project => {
   return  projectList?.map(name => {
      if (project.id === name.id) {
        return (
          <Typography variant="body2" gutterBottom classes={{}}>
            {`${name.name}`}
          </Typography>
        );
      }
      return null
    });
    
  })}
</DetailsBox>
Related