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

2
  • I removed it, still getting the same error Commented Jun 9, 2020 at 18:49
  • if i put ";" after the closing statement of catch block, i m getting "parsing error" ,")" expected Commented Jun 9, 2020 at 18:51

1 Answer 1

1

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);
    });
  }
});
Sign up to request clarification or add additional context in comments.

1 Comment

But i think I should not iterate the values inside the method. This is calling the method equal to number of items present in the array!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.