'Can we execute code inside setState apart from returning state object.?
I have scenario where i have to set state for two of the properties and i need to get an updated response by passing previous state to a method. I think this approach is fine,
`updateResponse = (updatedRecord, status) => {
this.setState(prevState => ({
userResponse: getUpdatedResponse(prevState.userResponse, updatedRecord, status),
userCount: getUpdatedResponse(prevState.userResponse, updatedRecord, status).filter(record => record.status === 'NEW').length,
}));
}`
To reduce multiple calls to getUpdatedResponse(), can i call the method getUpdatedResponse() only once, save its response to constant and then return an object inside setState?
updateResponse = (updatedRecord, status) => {
this.setState(prevState => {
const updatedResponse = getUpdatedResponse(prevState.userResponse, updatedRecord, status);
return {
userResponse: updatedResponse,
userCount: updatedResponse.filter(record => record.status === 'NEW').length,
}
});
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
