Skip to content

Commit

Permalink
Merge pull request #1581 from Vizzuality/MRXN23-501-minor-bugs-in-inv…
Browse files Browse the repository at this point in the history
…entory

[MRXN23-501]: delays cache invalidation of WDPAs
  • Loading branch information
andresgnlez authored Nov 20, 2023
2 parents 85f19b0 + 6fd8747 commit 8fa872e
Show file tree
Hide file tree
Showing 6 changed files with 63 additions and 58 deletions.
9 changes: 8 additions & 1 deletion app/hooks/wdpa/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { useMutation, useQuery, QueryObserverOptions, useQueryClient } from 'rea

import { AxiosRequestConfig } from 'axios';
import { useSession } from 'next-auth/react';
import { useDebouncedCallback } from 'use-debounce';

import { Project } from 'types/api/project';
import { Scenario } from 'types/api/scenario';
Expand Down Expand Up @@ -148,6 +149,10 @@ export function useUploadWDPAsShapefile({
const queryClient = useQueryClient();
const { data: session } = useSession();

const delayedInvalidateQueryCache = useDebouncedCallback(async (id: Project['id']) => {
await queryClient.invalidateQueries(['wdpas', id]);
}, 550);

const uploadWDPAShapefile = ({ id, data }: { id: Project['id']; data: FormData }) => {
return UPLOADS.request<{ success: true }>({
url: `/projects/${id}/protected-areas/shapefile`,
Expand All @@ -163,7 +168,9 @@ export function useUploadWDPAsShapefile({
return useMutation(uploadWDPAShapefile, {
onSuccess: async (data, variables) => {
const { id: projectId } = variables;
await queryClient.invalidateQueries(['wdpas', projectId]);
// ? It takes the API a little bit to get the final list of WDPAs updated
// ? after uploading a shapefile, so we need to delay the cache invalidation a few milliseconds
await delayedInvalidateQueryCache(projectId);
},
});
}
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@ const InventoryPanelProtectedAreas = ({
search,
},
{
keepPreviousData: true,
placeholderData: [],
}
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import React, { useCallback, useEffect, useRef, useState } from 'react';

import { useDropzone, DropzoneProps } from 'react-dropzone';
import { Form as FormRFF, Field as FieldRFF, FormProps } from 'react-final-form';
import { useQueryClient } from 'react-query';

import { useRouter } from 'next/router';

Expand Down Expand Up @@ -50,7 +49,6 @@ export const WDPAUploadModal = ({
const { pid } = query as { pid: string };

const { addToast } = useToasts();
const queryClient = useQueryClient();

const uploadWDPAsShapefileMutation = useUploadWDPAsShapefile({});

Expand Down Expand Up @@ -114,57 +112,58 @@ export const WDPAUploadModal = ({
data.append('file', file);
data.append('name', name);

const mutationResponse = {
onSuccess: () => {
setSuccessFile({ ...successFile });
onClose();
addToast(
'success-upload-wdpa-file',
<>
<h2 className="font-medium">Success!</h2>
<p className="text-sm">File uploaded</p>
</>,
{
level: 'success',
uploadWDPAsShapefileMutation.mutate(
{ data, id: pid },
{
onSuccess: () => {
setSuccessFile({ ...successFile });

addToast(
'success-upload-wdpa-file',
<>
<h2 className="font-medium">Success!</h2>
<p className="text-sm">File uploaded</p>
</>,
{
level: 'success',
}
);
onClose();
},
onError: (error: AxiosError | Error) => {
let errors: { status: number; title: string }[] = [];

if (isAxiosError(error)) {
errors = [...error.response.data.errors];
} else {
// ? in case of unknown error (not request error), display generic error message
errors = [{ status: 500, title: 'Something went wrong' }];
}
);
queryClient.invalidateQueries(['wdpas', pid]);
},
onError: (error: AxiosError | Error) => {
let errors: { status: number; title: string }[] = [];

if (isAxiosError(error)) {
errors = [...error.response.data.errors];
} else {
// ? in case of unknown error (not request error), display generic error message
errors = [{ status: 500, title: 'Something went wrong' }];
}

setSuccessFile(null);

addToast(
'error-upload-wdpa-csv',
<>
<h2 className="font-medium">Error</h2>
<ul className="text-sm">
{errors.map((e) => (
<li key={`${e.status}`}>{e.title}</li>
))}
</ul>
</>,
{
level: 'error',
}
);
},
onSettled: () => {
setLoading(false);
},
};

uploadWDPAsShapefileMutation.mutate({ data, id: `${pid}` }, mutationResponse);
setSuccessFile(null);

addToast(
'error-upload-wdpa-csv',
<>
<h2 className="font-medium">Error</h2>
<ul className="text-sm">
{errors.map((e) => (
<li key={`${e.status}`}>{e.title}</li>
))}
</ul>
</>,
{
level: 'error',
}
);
},
onSettled: () => {
setLoading(false);
},
}
);
},
[pid, addToast, onClose, uploadWDPAsShapefileMutation, successFile, queryClient]
[pid, addToast, onClose, uploadWDPAsShapefileMutation, successFile]
);

const { getRootProps, getInputProps, isDragActive, isDragAccept, isDragReject } = useDropzone({
Expand Down
2 changes: 1 addition & 1 deletion app/layout/projects/show/map/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ export const ProjectMap = (): JSX.Element => {

const protectedAreaQuery = useProjectWDPAs(
pid,
{},
{ sort: 'name' },
{
select: (data) => data.map(({ id }) => id),
}
Expand Down
6 changes: 3 additions & 3 deletions app/layout/projects/show/map/legend/hooks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ export const useConservationAreasLegend = () => {

const protectedAreaQuery = useProjectWDPAs(
pid,
{},
{ sort: 'name' },
{
select: (data) => data.map(({ id, name }) => ({ id, name })),
}
Expand Down Expand Up @@ -140,14 +140,14 @@ export const useFeaturesLegend = () => {
[]
).map((feature) => ({
...feature,
color: featureColorQueryState.data?.find(({ id }) => id === feature.id)?.color,
color: featureColorQueryState?.data?.find(({ id }) => id === feature.id)?.color,
})),
continuousFeatures: (
data?.filter(({ amountRange }) => amountRange.min !== null && amountRange.max !== null) ||
[]
).map((feature) => ({
...feature,
color: featureColorQueryState.data?.find(({ id }) => id === feature.id)?.color,
color: featureColorQueryState?.data?.find(({ id }) => id === feature.id)?.color,
})),
}),
enabled: featureColorQueryState?.status === 'success',
Expand Down
4 changes: 2 additions & 2 deletions app/layout/scenarios/edit/map/legend/hooks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ export const useFeaturesLegend = () => {
) || []
).map((feature) => ({
...feature,
color: featureColorQueryState.data?.find(({ id }) => id === feature.id)?.color,
color: featureColorQueryState?.data?.find(({ id }) => id === feature.id)?.color,
})),
continuousFeatures: (
data?.filter(
Expand All @@ -165,7 +165,7 @@ export const useFeaturesLegend = () => {
) || []
).map((feature) => ({
...feature,
color: featureColorQueryState.data?.find(({ id }) => id === feature.id)?.color,
color: featureColorQueryState?.data?.find(({ id }) => id === feature.id)?.color,
})),
}),
enabled:
Expand Down

0 comments on commit 8fa872e

Please sign in to comment.