From 6d290e813021aeb7dc816a391eb9547f05597bd5 Mon Sep 17 00:00:00 2001 From: Stig Ofstad Date: Thu, 23 May 2024 10:35:53 +0200 Subject: [PATCH] fix(form): wait for background fetch --- packages/dm-core-plugins/src/form/FormPlugin.tsx | 11 ++++++----- packages/dm-core/src/hooks/useDocument.tsx | 7 ++++--- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/packages/dm-core-plugins/src/form/FormPlugin.tsx b/packages/dm-core-plugins/src/form/FormPlugin.tsx index e0b101d4f..f040e449e 100644 --- a/packages/dm-core-plugins/src/form/FormPlugin.tsx +++ b/packages/dm-core-plugins/src/form/FormPlugin.tsx @@ -7,11 +7,12 @@ import { import { Form } from './components/Form' export const FormPlugin = (props: IUIPlugin) => { - const { document, isLoading, updateDocument, error } = useDocument( - props.idReference, - 0 - ) - if (isLoading) return + const { document, isLoading, updateDocument, error, isFetching } = + useDocument(props.idReference, 0) + + // react-hook-form is unable to rerender when the document is updated. + // This means that the form will not benefit from react-query caching. + if (isLoading || isFetching) return if (error) throw new Error(JSON.stringify(error, null, 2)) diff --git a/packages/dm-core/src/hooks/useDocument.tsx b/packages/dm-core/src/hooks/useDocument.tsx index 85f58cea3..39db47339 100644 --- a/packages/dm-core/src/hooks/useDocument.tsx +++ b/packages/dm-core/src/hooks/useDocument.tsx @@ -9,6 +9,7 @@ import { useState } from 'react' interface IUseDocumentReturnType { document: T | null isLoading: boolean + isFetching: boolean // react-query boolean, same as 'isLoading', but also includes background fetching updateDocument: ( newDocument: T, notify: boolean, @@ -57,15 +58,14 @@ export function useDocument( const { dmssAPI } = useApplication() const [errorResponse, setErrorResponse] = useState(null) const queryClient = useQueryClient() - const queryKeys = ['documents', idReference, depth] const documentDepth: number = depth ?? 0 if (documentDepth < 0 || documentDepth > 999) throw new Error('Depth must be a positive number < 999') - const { isPending, data } = useQuery({ + const { isPending, data, isFetching } = useQuery({ staleTime: 5 * 1000, - refetchOnMount: false, + refetchOnMount: true, queryKey: queryKeys, queryFn: () => dmssAPI @@ -119,6 +119,7 @@ export function useDocument( return { document: data || null, isLoading: isPending, + isFetching: isFetching, updateDocument: (newDocument: T, notify, partialUpdate) => mutation.mutateAsync({ newDocument, notify, partialUpdate }), error: errorResponse,