Revise: Anticipated output missing at conclusion of arrow function

Here is the code snippet that I am having trouble with:

<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>

I encountered an error which says

Expected to return a value at the end of arrow function
. I understand that this is because of the return in an anonymous function, but how can I refactor it to fix the issue?

Edit: The error points to this specific line: projectList?.map(name => {

Answer №1

The original function provided does not return a value, so you have two options: use parentheses for an implicit return or add an explicit return statement:

Implicit Return example:

<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 example:

<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>

Answer №2

The caution is prompted because intermittently you are not returning anything from the .map function; as a result, the array may sometimes contain elements of undefined alongside Typography components.

Consider using .filter instead to remove IDs that do not 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>

Alternatively, if there is likely only one match for each pair, consider creating an object or Map linking IDs to either the projects items or the projectList items - this will decrease computational complexity from O(n ^ 2) to O(n).

Answer №3

Give it a shot

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Assistance with Javascript Objects Using JSON and AJAX

Currently, I am utilizing Ajax to retrieve data from my Json file. A problem I am facing is that in one particular div of my html, I need to include both a heading and a paragraph. I attempted to create a property like so: "headingpara": "<h1> blah ...

Can the installation of Canvas be done on a device with the M1 chip?

When attempting to install canvas on a MacBook Pro M1 using the command: npm install --save-dev canvas An error is displayed: npm ERR! code 1 npm ERR! path /Users/xiaoqiangjiang/source/reddwarf/frontend/js-wheel/node_modules/canvas ... (error message con ...

retrieve an item that lacks a definitive value

Here's an object I have: Obj = { foo: false, bar: true, private: { something: 'else' } } Now, I'm trying to return this object without the private part. Since the private part is used elsewhere and cannot be spliced out, I ...

Unable to access style property, encountering error on separate page

Once again, I'm feeling a bit lost on where to go with this coding issue. It seems quite basic, but I'm struggling to pinpoint the problem. My goal is to hide several IDs, and while it does work, I keep encountering an error: Uncaught TypeError: ...

Different Ways to Access an Array in an EJS Template

After receiving a list of IDs from an API, I need to include them in a URL within an EJS template to retrieve the correct items. For example, the URL format is: Here are some example IDs: 526 876 929 The desired output inside the EJS template: <li&g ...

Differentiating Between Observables and Callbacks

Although I have experience in Javascript, my knowledge of Angular 2 and Observables is limited. While researching Observables, I noticed similarities to callbacks but couldn't find any direct comparisons between the two. Google provided insights into ...

Utilizing AngularJS: Establishing a Universal Parent State in UI-Router for Modals and Shared Components

In my code using UI-Router and Bootstrap-ui modal, I have defined the state as shown below. reference var state = { name: 'modala', parent: 'home', onEnter: function($modal, $state) { modalInstance = $modal.open({ ...

Retrieve the value with `eventArgs.get_value()` function to obtain the selected text instead of the ID

When I populate a textbox with autocomplete using the code below, it only returns the selected text and not the rowid. Any idea why alert(eventArgs.get_value()) doesn't return the actual ID of the row in SQL? <script language="javascript" type="te ...

How can I utilize the "remark" tool to handle Markdown files with URLs that don't adhere to Markdown formatting? Are there any supplemental plugins available for this

My markdown file has frontmatter and sometimes includes inline URLs that are not properly formatted with markdown syntax. I'm looking for a way to handle these non-markdown URLs within the markdown file - possibly by parsing them into HTML URLs using ...

Construct object in JavaScript recursively

My current project involves creating a file structure index using nodeJS. I am utilizing the fs.readir function to iterate through files and it is working smoothly. However, I am facing an issue when it comes to descending into the directory structure and ...

Is it possible to customize the appearance of the selected item in a select box? Can the selected value be displayed differently from the other options?

My current project involves working with the antd' select box. I have been trying to customize the content inside the Option which usually contains regular text by incorporating some JSX into it. The output currently looks like this: https://i.sstati ...

Tips on resetting the position of a div after filtering out N other divs

Check out this code snippet. HTML Code: X.html <input type="text" id="search-criteria"/> <input type="button" id="search" value="search"/> <div class="col-sm-3"> <div class="misc"> <div class="box box-info"> ...

error": "message": "Property 'name' cannot be read because it is undefined

I've encountered an issue while creating a route to handle POST data. Despite testing it on postman, I have not been able to find a solution for the problem that many others seem to be facing as well. It seems like the 'name' field is not be ...

Is there a way for me to showcase a collection of pictures in an array format

I am facing an issue on my react page where the data is successfully fetched from an API, but I am having trouble fetching the array of images. Below is the code snippet that I have written: import React, {Component} from 'react'; export defaul ...

What is the proper way to encode URL parameters for a REST API request?

When working on a REST API call, I needed to create some URL parameters using Angularjs 1.4.2. To achieve this, I utilized a form to pass the parameters to a service function which handles building the parameters and making the $http.post call to the API. ...

What are some ways to expand the width of a MaterialUI form control if no value has been chosen?

I am currently working on a project where I need a dropdown menu component with specific selections. However, the layout appears to be cramped and I'm struggling to adjust the width. Additionally, I've been unsuccessful in changing the font size ...

What is the best way to connect my Typescript NextJS code to my Express API?

My goal is to extract data from my API, which is providing the following JSON: [ { project: "Challenges_jschallenger.com" }, { project: "Using-Studio-Ghilis-API-With-JS-Only" }, { project: "my-portfolio-next" }, { proj ...

Creating Dynamic Divs in ASP.NET

Attempting to dynamically create a Div by clicking a button has been a challenge for me. I found a helpful link here: After referring to the link, I created the following code on the server side (.cs page): public static int i = 0; protected void Bu ...

Creating dynamic routes in React by pulling data from a JSON file

Creating multiple routes based on JSON data file is the goal: routes.jsx import React from 'react'; import { Route, Router, IndexRoute } from 'react-router'; import ReactDOM from 'react-dom'; import App from './index.j ...

Are your divs getting truncated?

Currently faced with a perplexing issue where inserting elements into a div causes scaling problems, resulting in most of the divs being cut off. This glitch occurs when two new elements are added. Despite changing page sizes and thoroughly debugging by o ...