How can I loop through an array to display the value?
Here is my following code:
ineligiblePointsTableRows() {
return this.state[PointsTableType.INELIGIBLE].contracts.map(contract => {
return {
applied: (<input
value={0}
disabled
className="applied-pts-input"
/>),
reason: (
<div className="ineligible-reason-container">
<i className="fa fa-exclamation-triangle"></i>
<p aria-label={contract.reason}>{contract.reason.map((reason: any, i: any) => (
<text>Hello world</text>
))}</p>
</div>
),
},
};
});
}
I got error at line contract.reason.map
Object is possibly 'undefined'.ts(2532) (parameter) contract: ContractUsage No quick fixes available
when I console.log(contract.reaons)
this is the value:
Array(2)
0: "Cannot borrow usage this far in the future."
1: "Contract has a past due balance."
So my goal is i am trying to loop through contract.reason but I am having error like above. How can I fix this ?
CodePudding user response:
It's a typescript error telling you that the object might be "undefined", or in other words, might be empty of any value.
Few possible ways to solve this:
1.
ineligiblePointsTableRows() {
return this.state[PointsTableType.INELIGIBLE].contracts.map(contract => {
return {
applied: (<input
value={0}
disabled
className="applied-pts-input"
/>),
reason: (
<div className="ineligible-reason-container">
<i className="fa fa-exclamation-triangle"></i>
<p aria-label={contract?.reason}>{contract?.reason?.map((reason: any, i: any) => (
<text>Hello world</text>
))}</p>
</div>
),
},
};
});
}
ineligiblePointsTableRows() {
return this.state[PointsTableType.INELIGIBLE].contracts.map(contract => {
return {
applied: (<input
value={0}
disabled
className="applied-pts-input"
/>),
reason: (
<div className="ineligible-reason-container">
<i className="fa fa-exclamation-triangle"></i>
{contract !== undefined && <p aria-label={contract.reason}>{contract.reason.map((reason: any, i: any) => (
<text>Hello world</text>
))}</p>}
</div>
),
},
};
});
}
CodePudding user response:
It means that your contract
or contract.reason
is possibly undefined. To avoid the error use optional chaining
like this:
contract?.reason?.map