Singh
Singh

Reputation: 207

Iterate the items of array & null check inside a method call in Reactjs

interface State {
  detailsItem: Array<{
    id: string;
    name: string;
designation: string;
  }>;

interface Props{
id: string;
name: string;
desgination:string
}

Method:

sampleItem = () => {
  this.sampleService
    .sampleMethod(this.props.id, this.props.name, this.props.designation)
    .then((response) => {})
    .catch((error) => {
      console.log(error);
    });
};

I want to replace props and i want to fetch id,name & designation from the array of detailsItem.In the below method, I am trying doing that, but getting an error

sampleItemOne = () => {
  this.state.detailsItem.map((item) => {
    { item? ( 
            this.sampleService
            .sampleMethod(item.id, item.name, item.designation)
            .then((response) => {})
            .catch((error) => {
              console.log(error);
            })
        : null;
    }
  });
};

I tried removing the props & calling the id, name & designation in sampleItemOne but getting an error: Expected an assignment or function call and instead saw an expression Can anyone please help me with this, what I am doing wrong!

Upvotes: 1

Views: 75

Answers (1)

Brian Thompson
Brian Thompson

Reputation: 14355

In the below piece of code, you added an extra {} around your ternary. This is probably because you're used to using that within JSX to denote an expression, but in a function body like this, its object notation.

this.state.detailsItem.map((item) => {
  {item ? ( 
    this.sampleService
    .sampleMethod(item.id, item.name, item.designation)
    .then((response) => {})
    .catch((error) => {
      console.log(error);
    })
  : null;
  }
});

This is breaking because the above code is not a valid object.

Instead just use a regular if (its more readable anyway)

this.state.detailsItem.map((item) => {
  if(item) { 
    this.sampleService
    .sampleMethod(item.id, item.name, item.designation)
    .then((response) => {})
    .catch((error) => {
      console.log(error);
    });
  }
});

Upvotes: 1

Related Questions