aditya kumar
aditya kumar

Reputation: 3023

How to check for undefined in reactjs mapping

I am working on a app which fetches data using axios after that it stores this it in redux store. Everything works fine if data is available from the api endpoint but the problem arise when i am getting no data it gives me error saying this.

TypeError: props.teamProduct._embedded is undefined

This is how my data looks on successfull call

successfull

when i get undefined result

undefined

Here is my code

This is how I am getting team list from store

const mapStateToProps = (state) => {
  return {
    
    team: state.productDetails.team.team.data,
  };
};

After that i m passing this to component

productDetail

{teamProduct &&
              teamProduct._embedded.cartResourceList.map((item, index) => {
                console.log("item", item);
                if (index < 2) {
                  return (
                    <Grid
                      key={index}
                      container
                      item
                      xs={12}
                      className="mid_box"
                    >
                      <Grid container item xs={6}>
                      
                      </Grid>
                    </Grid>
                  );
                }
              })}

Is there any way to check for undefined value here.

Upvotes: 0

Views: 29

Answers (1)

Drew Reese
Drew Reese

Reputation: 202836

Need to check all property accesses to the one you actually need

{teamProduct && 
  teamProduct._embedded &&
  teamProduct._embedded.cartResourceList &&
  teamProduct._embedded.cartResourceList.map((item, index) => {
    console.log("item", item);
    if (index < 2) {
      return (
        <Grid
          key={index}
          container
          item
          xs={12}
          className="mid_box"
        >
          <Grid container item xs={6}></Grid>
        </Grid>
      );
    }
  })
}

Upvotes: 1

Related Questions