Reputation: 699
I am trying to console my data onApplyClick
event. It is working fine when I am passing all the data but when I an trying to pass data conditionally then it is throwing error.
My main component code is
<MyComponent
onApplyClick={(
myData: First & {
newData: Second;
}
) => console.log(myData)}
getData={getData}
/>
Where First & Second is an interface. Now I am passing all data using onApplyClick
event like -
onApplyClick={() => {
let AData= {
first: "one",
second: "two
};
onApplyClick({
newData: AData,
Bdata: "three",
Cdata: "four"
});
}}
Second interface is -
export interface Second {
first : string;
second: string;
}
First interface is -
export interface First {
Bdata? : string;
Cdata? :string;
}
now I want to pass Bdata if a condition is true & if condition is false then I want to pass Cdata onApplyClick
.
I am trying pass data using this code -
onApplyClick({
newData: AData,
if(condition==true) {
Bdata: "three",
}
else {
Cdata: "four"
}
});
I am getting error while passing the condition inside an onApplyClick
event. How can I pass data conditionally ?
Upvotes: 0
Views: 674
Reputation: 143
I think that the best approach in this case would be to create two callbacks with defferetnt data.
Or create condition with data:
const data = condition ? data1: data2;
And then pass it in callback.
onClick={() => callback(data)}
Best regards.
Upvotes: 2
Reputation: 529
You can't have conditionals inside an object. What you need to do is take that condition outside of the object and return different objects in each clause.
onApplyClick( condition ? {newData: AData, Bdata: "three"} : {newData: AData, Cdata: "four"} )
Upvotes: 0
Reputation: 1764
try this
<MyComponent
onApplyClick={( condition ? { myData: First}:{ newData: Second}) => console.log(myData)}
getData={getData}
/>
Upvotes: 0