'Running async multiple functions with onClick
I am running an event where when you click, it will log out the click. However I have noticed you need to click twice. This, in my belief is because it first sets the selectedRole state, then on the second click, actions the second action.
How would you improve this, potentially with an async function to await the first onClick, or wrap into one?
Firstly, our component which pulls through roles on the basis of data in a redux store
const SearchResultsText = ({ role }) => {
return (
<JobContainer className={role}>
<JobSearchTypography className={role}>
{role}
</JobSearchTypography>
</JobContainer>
);
};
Secondly, there is an onClick which will console.log the onClick, this does work.
(<IndividualContainer onClick={() => {
setSelectedRole(result)
onClickTrial()
}
}>
<SearchResultsText role={result} />
</IndividualContainer>
My secondary onClick function is below.
const onClickTrial = () => {
setLoading(true)
console.log(selectedRole)
finalAsyncRoleSelection(dispatch, selectedRole);
setLoading(false)
setTerm('')
}
I believe my troubleshooting is correct, I just am not sure how to correct it.I assume I need to execute function 1, then async function the secondary portion, is this correct?
Solution 1:[1]
Try chaning your code to something like this:
<IndividualContainer onClick={() => onClickTrial(result)}>
<SearchResultsText role={result} />
</IndividualContainer>;
const onClickTrial = (role) => {
setLoading(true);
setSelectedRole(role);
console.log(role);
finalAsyncRoleSelection(dispatch, role);
setLoading(false);
setTerm("");
};
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 | Taghi Khavari |
