Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - Can't use Try Catch block within .map (returning the jsx from within the try catch)

Code is the following:

   return (
    <MuiThemeProvider>
      <GridList>

      {singleProd.map(function(product) {
        // console.log(product)
        let fileID;

        try {
          api.GetFile(product.relationships.main_image.data.id)

          .then((file) => {
            fileID = file.data.link.href;
            console.log(fileID)

            return (
                <Tile name={product.name} id={product.id} link={fileID} key={product.id} />
            )

          })
        }

        catch(e){
          console.log('product has no main image');

          return (
              <Tile name={product.name} id={product.id} link={fileID} key={product.id} />
          )
        }

      })}
      </GridList>
    </MuiThemeProvider>
   )

Error is: Cannot read property '_currentElement' of null

The diagnosis so far is that nothing is being returned for the .map function, because the returns are each wrapped in try catch blocks respectively.

If you add a return outside the try catch, it will succeed.

Wondering how I should format this so that each of the objects in the .map is run through the try catch. If the try succeeds, then that jsx is returned and used. If it doesn't, then the catch jsx is returned and used.

Any ideas how I might restructure the code above?

Other relevant info:

  • using material UI Tiles
  • using external API calls which return an array of objects, hence the map
  • the tile for each object is returned and becomes part of the gridList.
like image 856
Matthew Foyle Avatar asked Nov 28 '25 23:11

Matthew Foyle


1 Answers

The try/catch is not really the issue here I think. A few things to consider:

  1. You should not do an API call inside the render function. That will cause it to request multiple times, anytime the component re-renders.
  2. Your API call is asynchronous, so you will need to wait for the response to get the data you want.

The asynchronous bit is what's causing the current error I believe, because the .map doesn't have any data until the request finishes.

--

What you should do is:

  1. Call the API from componentDidMount
  2. Use setState to set the response data in your components state, and then render that result.

Even better would be to use something like redux to maintain your application state.

like image 165
Austin Greco Avatar answered Nov 30 '25 11:11

Austin Greco



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!