From 80a170d93cb68806cc8bbdf4762e226224437c93 Mon Sep 17 00:00:00 2001 From: Oliver Date: Mon, 16 Oct 2023 23:54:28 +1100 Subject: [PATCH] Improve useInstance hook (#5710) - Allow use without primary key - Allow default value to be customizedr --- src/frontend/src/hooks/UseInstance.tsx | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/src/frontend/src/hooks/UseInstance.tsx b/src/frontend/src/hooks/UseInstance.tsx index 377cd7da27..7dbf10bfa4 100644 --- a/src/frontend/src/hooks/UseInstance.tsx +++ b/src/frontend/src/hooks/UseInstance.tsx @@ -17,23 +17,29 @@ export function useInstance({ endpoint, pk, params = {}, + defaultValue = {}, + hasPrimaryKey = true, refetchOnMount = false, refetchOnWindowFocus = false }: { endpoint: ApiPaths; - pk: string | undefined; + pk?: string | undefined; + hasPrimaryKey?: boolean; params?: any; + defaultValue?: any; refetchOnMount?: boolean; refetchOnWindowFocus?: boolean; }) { - const [instance, setInstance] = useState({}); + const [instance, setInstance] = useState(defaultValue); const instanceQuery = useQuery({ queryKey: ['instance', endpoint, pk, params], queryFn: async () => { - if (pk == null || pk == undefined || pk.length == 0) { - setInstance({}); - return null; + if (hasPrimaryKey) { + if (pk == null || pk == undefined || pk.length == 0) { + setInstance(defaultValue); + return null; + } } let url = apiUrl(endpoint, pk); @@ -48,12 +54,12 @@ export function useInstance({ setInstance(response.data); return response.data; default: - setInstance({}); + setInstance(defaultValue); return null; } }) .catch((error) => { - setInstance({}); + setInstance(defaultValue); console.error(`Error fetching instance ${url}:`, error); return null; });