mirror of
https://github.com/inventree/InvenTree.git
synced 2025-05-02 13:28:49 +00:00
Improve useInstance hook (#5710)
- Allow use without primary key - Allow default value to be customizedr
This commit is contained in:
parent
9705521cd2
commit
80a170d93c
@ -17,24 +17,30 @@ 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<any>({});
|
||||
const [instance, setInstance] = useState<any>(defaultValue);
|
||||
|
||||
const instanceQuery = useQuery({
|
||||
queryKey: ['instance', endpoint, pk, params],
|
||||
queryFn: async () => {
|
||||
if (hasPrimaryKey) {
|
||||
if (pk == null || pk == undefined || pk.length == 0) {
|
||||
setInstance({});
|
||||
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;
|
||||
});
|
||||
|
Loading…
x
Reference in New Issue
Block a user