Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
20
rated 0 times [  25] [ 5]  / answers: 1 / hits: 17062  / 5 Years ago, tue, may 14, 2019, 12:00:00

I am using typescript with react, and I get this error.



Cannot invoke an object which is possibly 'undefined'.ts(2722)
const onChange: ((...args: any[]) => any) | undefined


Here is my code where I get the errors.



interface FilterGroupsProps {
data?: any[];
selectedGroups?: any[];
onChange?: (...args: any[]) => any;
}

// Inside the class
onClick = (groupName: string) => (event: MouseEvent<HTMLButtonElement>) => {
const { onChange } = this.props;
event.preventDefault();
onChange(groupName);
};

//Inside the render:
{allUniqueGroups.map((group: string) => (
<a
key={group}
className=dropdown-item d-flex justify-content-between align-items-center
href=#
onClick={this.onClick(group)}
>


What I do not understand with this error is the following: The groupName should be available when this onClick is rendered.



Which means I am kind of confused where my security case should be handled. Can you explain the problem here? As well as provide me with a solution to this problem.


More From » reactjs

 Answers
6

Take a look at FilterGroupsProps:


interface FilterGroupsProps {
data?: any[];
selectedGroups?: any[];
onChange?: (...args: any[]) => any;
}

onChange is possibly undefined or provided.


Here is my approach:


onClick = (groupName: string) => (event: MouseEvent<HTMLButtonElement>) => {
if (this.props.onChange) {
const { onChange } = this.props;
event.preventDefault();
onChange(groupName);
}
// or do something else...
};

Or solution from comments by Randy to remove optional flag from onChange method:


interface FilterGroupsProps {
data?: any[];
selectedGroups?: any[];
onChange: (...args: any[]) => any;
}

[#52121] Tuesday, May 7, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
brynn

Total Points: 448
Total Questions: 83
Total Answers: 118

Location: Albania
Member since Sun, Nov 22, 2020
4 Years ago
brynn questions
Wed, Sep 22, 21, 00:00, 3 Years ago
Wed, Dec 23, 20, 00:00, 4 Years ago
Wed, Aug 12, 20, 00:00, 4 Years ago
;