Skip to content

Commit

Permalink
disable mutation when there is no changes an add info toast
Browse files Browse the repository at this point in the history
  • Loading branch information
anamontiaga committed Dec 18, 2023
1 parent cdeb9c9 commit 5bd4613
Show file tree
Hide file tree
Showing 2 changed files with 141 additions and 115 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { useDebouncedCallback } from 'use-debounce';

import { useSaveSelectedFeatures, useSelectedFeatures, useTargetedFeatures } from 'hooks/features';
import { useCanEditScenario } from 'hooks/permissions';
import { useSaveScenario, useScenario } from 'hooks/scenarios';
import { useToasts } from 'hooks/toast';

import Button from 'components/button';
import ConfirmationPrompt from 'components/confirmation-prompt';
Expand All @@ -26,6 +26,8 @@ export const ScenariosFeaturesTargets = ({ onGoBack }: { onGoBack: () => void })
const [confirmationTarget, setConfirmationTarget] = useState(null);
const [confirmationFPF, setConfirmationFPF] = useState(null);

const { addToast } = useToasts();

const queryClient = useQueryClient();
const { query } = useRouter();
const { pid, sid } = query as { pid: string; sid: string };
Expand All @@ -39,11 +41,6 @@ export const ScenariosFeaturesTargets = ({ onGoBack }: { onGoBack: () => void })
const editable = useCanEditScenario(pid, sid);

const selectedFeaturesMutation = useSaveSelectedFeatures({});
const saveScenarioMutation = useSaveScenario({
requestConfig: {
method: 'PATCH',
},
});

const { data: selectedFeaturesData } = useSelectedFeatures(sid, {});

Expand All @@ -53,9 +50,6 @@ export const ScenariosFeaturesTargets = ({ onGoBack }: { onGoBack: () => void })
isFetched: targetedFeaturesIsFetched,
} = useTargetedFeatures(sid);

const { data: scenarioData } = useScenario(sid);
const { metadata } = scenarioData || {};

const INITIAL_VALUES = useMemo(() => {
return {
features: targetedFeaturesData,
Expand Down Expand Up @@ -137,76 +131,93 @@ export const ScenariosFeaturesTargets = ({ onGoBack }: { onGoBack: () => void })
}, []);

const onSubmit = useCallback(
(values) => {
setSubmitting(true);
(values, form) => {
const { features } = values;

const data = {
status: 'created',
features: selectedFeaturesData.map((sf) => {
const { featureId, kind, geoprocessingOperations } = sf;

if (kind === 'withGeoprocessing') {
const featuresFieldTouched = form.getFieldState('features')?.dirty;

if (featuresFieldTouched) {
setSubmitting(true);

const data = {
status: 'created',
features: selectedFeaturesData.map((sf) => {
const { featureId, kind, geoprocessingOperations } = sf;

if (kind === 'withGeoprocessing') {
return {
featureId,
kind,
geoprocessingOperations: geoprocessingOperations.map((go) => {
const { splits } = go;

return {
...go,
splits: splits
.filter((s) => {
return features.find((f) => {
return f.parentId === featureId && f.value === s.value;
});
})
.map((s) => {
const { target, fpf } = features.find((f) => {
return f.parentId === featureId && f.value === s.value;
});

return {
...s,
marxanSettings: {
prop: target / 100 || 0.5,
fpf,
},
};
}),
};
}),
};
}

const { target, fpf = 1 } = features.find((f) => f.featureId === featureId);
return {
featureId,
kind,
geoprocessingOperations: geoprocessingOperations.map((go) => {
const { splits } = go;

return {
...go,
splits: splits
.filter((s) => {
return features.find((f) => {
return f.parentId === featureId && f.value === s.value;
});
})
.map((s) => {
const { target, fpf } = features.find((f) => {
return f.parentId === featureId && f.value === s.value;
});

return {
...s,
marxanSettings: {
prop: target / 100 || 0.5,
fpf,
},
};
}),
};
}),
marxanSettings: {
prop: target / 100 || 0.5,
fpf,
},
};
}
}),
};

const { target, fpf = 1 } = features.find((f) => f.featureId === featureId);
return {
featureId,
kind,
marxanSettings: {
prop: target / 100 || 0.5,
fpf,
},
};
}),
};

selectedFeaturesMutation.mutate(
{
id: `${sid}`,
data,
},
{
onSuccess: async () => {
await queryClient.invalidateQueries(['selected-features', sid]);
},
onSettled: () => {
setSubmitting(false);
selectedFeaturesMutation.mutate(
{
id: `${sid}`,
data,
},
}
);
{
onSuccess: async () => {
await queryClient.invalidateQueries(['selected-features', sid]);
},
onSettled: () => {
setSubmitting(false);
},
}
);
}
if (!featuresFieldTouched) {
addToast(
'save-selected-features',
<>
<h2 className="font-medium"></h2>
<p className="text-sm">No modifications have been made to the selected features.</p>
</>,
{
level: 'info',
}
);
}
},
[sid, queryClient, selectedFeaturesData, selectedFeaturesMutation]
[sid, queryClient, selectedFeaturesData, selectedFeaturesMutation, addToast]
);

const toggleSeeOnMap = useCallback(
Expand Down Expand Up @@ -253,7 +264,7 @@ export const ScenariosFeaturesTargets = ({ onGoBack }: { onGoBack: () => void })

return (
<FormRFF key="features-target" onSubmit={onSubmit} initialValues={INITIAL_VALUES}>
{({ handleSubmit, form, values }) => (
{({ handleSubmit, values }) => (
<form
onSubmit={handleSubmit}
autoComplete="off"
Expand Down Expand Up @@ -364,7 +375,7 @@ export const ScenariosFeaturesTargets = ({ onGoBack }: { onGoBack: () => void })
type="submit"
theme="primary"
size="lg"
disabled={submitting || !form.getFieldState('features')?.dirty}
disabled={submitting}
>
Save
</Button>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -120,51 +120,66 @@ export const WDPAThreshold = ({ onGoBack }: { onGoBack: () => void }): JSX.Eleme
const areProjectPAreasSelected = !!projectPAreasSelectedIds.length;

const handleSubmit = useCallback(
(values) => {
setSubmitting(true);

(values, form) => {
const { wdpaThreshold } = values;

saveScenarioProtectedAreasMutation.mutate(
{
id: `${sid}`,
data: {
areas: selectedProtectedAreas,
threshold: +(wdpaThreshold * 100).toFixed(0),
},
},
{
onSuccess: () => {
addToast(
'save-scenario-wdpa',
<>
<h2 className="font-medium">Success!</h2>
<p className="text-sm">Scenario protected areas threshold saved</p>
</>,
{
level: 'success',
}
);
},
onError: () => {
addToast(
'error-scenario-wdpa',
<>
<h2 className="font-medium">Error!</h2>
<p className="text-sm">Scenario protected areas threshold not saved</p>
</>,
{
level: 'error',
}
);
},
onSettled: () => {
setSubmitting(false);
const thresholdTouched = form.getFieldState('wdpaThreshold')?.dirty;

if (thresholdTouched) {
setSubmitting(true);
saveScenarioProtectedAreasMutation.mutate(
{
id: `${sid}`,
data: {
areas: selectedProtectedAreas,
threshold: +(wdpaThreshold * 100).toFixed(0),
},
},
}
);
{
onSuccess: () => {
addToast(
'save-scenario-wdpa',
<>
<h2 className="font-medium">Success!</h2>
<p className="text-sm">Scenario protected areas threshold saved</p>
</>,
{
level: 'success',
}
);
},
onError: () => {
addToast(
'error-scenario-wdpa',
<>
<h2 className="font-medium">Error!</h2>
<p className="text-sm">Scenario protected areas threshold not saved</p>
</>,
{
level: 'error',
}
);
},
onSettled: () => {
setSubmitting(false);
},
}
);
}
if (!thresholdTouched) {
addToast(
'save-scenario-wdpa',
<>
<h2 className="font-medium"></h2>
<p className="text-sm">No modifications have been made to the protected areas.</p>
</>,
{
level: 'info',
}
);
}
},
[saveScenarioProtectedAreasMutation, selectedProtectedAreas, sid, addToast, onGoBack]
[saveScenarioProtectedAreasMutation, selectedProtectedAreas, sid, addToast]
);

useEffect(() => {
Expand Down Expand Up @@ -205,7 +220,7 @@ export const WDPAThreshold = ({ onGoBack }: { onGoBack: () => void }): JSX.Eleme
</h3>
</div>
<FormRFF onSubmit={handleSubmit} initialValues={INITIAL_VALUES}>
{({ values, handleSubmit: RFFhandleSubmit, form }) => {
{({ values, handleSubmit: RFFhandleSubmit }) => {
return (
<form
onSubmit={RFFhandleSubmit}
Expand Down Expand Up @@ -320,7 +335,7 @@ export const WDPAThreshold = ({ onGoBack }: { onGoBack: () => void }): JSX.Eleme
size="lg"
type="submit"
className="relative px-20 md:px-9 lg:px-16 xl:px-20"
disabled={submitting || !form.getFieldState('wdpaThreshold')?.dirty}
disabled={submitting}
>
<span>Save</span>
</Button>
Expand Down

0 comments on commit 5bd4613

Please sign in to comment.