Skip to content

Commit

Permalink
Fix buggy async callbacks (#360)
Browse files Browse the repository at this point in the history
  • Loading branch information
timwessman authored Sep 16, 2024
1 parent 955f34d commit 3844b48
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 11 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -250,11 +250,11 @@ const OpeningPeriodAccordion = ({
</button>
</div>
<ConfirmationModal
onConfirm={async (): Promise<void> => {
onConfirm={() => {
if (onDelete) {
setDeleting(true);
try {
await onDelete();
onDelete();
setDeleting(false);
toast.success({
label: t('ResourcePage.Notifications.PeriodRemoveSuccess', {
Expand Down
16 changes: 8 additions & 8 deletions src/pages/ResourceBatchUpdatePage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,8 @@ const ResourceBatchUpdatePage = ({
const targetResourceIDs = targetResourcesString.split(',');

const handleApiResponse = async (resources: Resource[]) => {
if (!isMounted) return;

// for some reason origins are not part of Resource type, this need to be fixed in API
const resourcesWithOrigins = resources as ResourceWithOrigins[];
const targetResources = targetResourceIDs
Expand Down Expand Up @@ -293,10 +295,8 @@ const ResourceBatchUpdatePage = ({
key: targetResourcesStorageKey,
value: newData,
});
if (isMounted) {
setTargetResourceData(newData);
setLoading(false);
}
setTargetResourceData(newData);
setLoading(false);
};

// fetch target resource data from api
Expand Down Expand Up @@ -337,10 +337,10 @@ const ResourceBatchUpdatePage = ({
api
.getResource(mainResourceId)
.then(async (r: Resource) => {
if (isMounted) {
setResource(r);
setLoading(false);
}
if (!isMounted) return;

setResource(r);
setLoading(false);
})
.catch((e: Error) => {
setLoading(false);
Expand Down
10 changes: 9 additions & 1 deletion src/pages/ResourcePage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -123,12 +123,16 @@ const ResourcePage = ({
}
}, [language, resource, targetResourcesString]);

useEffect((): void => {
useEffect(() => {
let isMounted = true;

// UseEffect's callbacks are synchronous to prevent a race condition.
// We can not use an async function as an useEffect's callback because it would return Promise<void>
api
.getResource(mainResourceId)
.then(async (r: Resource) => {
if (!isMounted) return;

setResource(r);
const resourceHasChildren = r.children.length > 0;
const resourceHasParents = r.parents.length > 0;
Expand All @@ -149,6 +153,10 @@ const ResourcePage = ({
setError(e);
setLoading(false);
});

return () => {
isMounted = false;
};
}, [mainResourceId]);

const gotoBatchUpdatePage = (): void => {
Expand Down

0 comments on commit 3844b48

Please sign in to comment.