'Calling multiple handler methods in react js onSubmit
I am working on a React JS project which uses a search form component with an onSubmit. I want to call multiple search handler methods which makes Axios calls to multiple backend APIs at the same time. I am using a class component, my onSubmit calls a searchHandler method which contains multiple axios calls to the backend. But when I submit the form I get an error: frontend error
This is my search handler function which my onSubmit calls, it contains two Axios calls:
applicationSearchHandler(event) {
event.preventDefault();
console.log(this.state.number, this.state.orgChoice);
LoanAppDataService.getPromoCodeExpiryInfo(
this.state.orgChoice,
this.state.promoCode,
this.state.number
)
.then((response) => {
if (response && response.data && response.data.length > 0) {
console.log(response.data[0].applicationId);
this.setState((state) => ({
...this.state,
expiryStatusMessage: response.data[0].message,
isSearched: true,
error: false,
}));
}
})
.catch((error) => {
this.setState({
error: !this.state.error,
errorAlert: "",
isSearched: false,
});
});
LoanAppDataService.getCorrectPromoCodeInfoEmailAndOrgId(
this.state.emailId,
this.state.orgChoice
)
.then((response) => {
this.setState((state) => ({
associatedPromoMessage: response.data[0].message,
isSearched: true,
error: false,
}));
})
.catch((error) => {
this.setState({
error: !this.state.error,
errorAlert: "",
isSearched: false,
});
});
this.setState((state) => ({
...this.state,
number: "",
customerName: "",
orgChoice: "",
}));
const isValid = this.validateSsn();
}
This is how my onSubmit looks like:
<form onSubmit={this.applicationSearchHandler}>
I don't exactly know how to rectify this error, I tried multiple approaches but nothing seems to be working for now.
Solution 1:[1]
You get an error In this part of your code
expiryStatusMessage: response.data[0].message
Most Probably response.data[0] is null or undefined and this code tries to find a message from null, So it gives Error
You can use nullish operator here like that
expiryStatusMessage: response.data[0]?.message
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
