refactor, security updates, cv extraction upgrades
This commit is contained in:
@@ -1,6 +1,8 @@
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import { api } from "../api";
|
||||
import { Company } from "../types";
|
||||
import { useViewResource, ViewResourceError } from "./useViewResource";
|
||||
|
||||
let cachedCompanies: Company[] | null = null;
|
||||
let inflight: Promise<Company[]> | null = null;
|
||||
@@ -10,7 +12,7 @@ async function fetchCompanies(): Promise<Company[]> {
|
||||
if (inflight) return inflight;
|
||||
|
||||
inflight = api
|
||||
.get<Company[]>("/companies")
|
||||
.get<Company[]>('/companies')
|
||||
.then((r) => {
|
||||
cachedCompanies = r.data;
|
||||
return r.data;
|
||||
@@ -26,25 +28,34 @@ export function invalidateCompaniesCache() {
|
||||
cachedCompanies = null;
|
||||
}
|
||||
|
||||
export function useCompanies() {
|
||||
const [companies, setCompanies] = useState<Company[]>(cachedCompanies ?? []);
|
||||
const [loading, setLoading] = useState(!cachedCompanies);
|
||||
export function useCompanies(): {
|
||||
companies: Company[];
|
||||
loading: boolean;
|
||||
refreshing: boolean;
|
||||
error: ViewResourceError | null;
|
||||
reload: () => Promise<void>;
|
||||
} {
|
||||
const [cacheBust, setCacheBust] = useState(0);
|
||||
const resource = useViewResource(fetchCompanies, {
|
||||
initialData: cachedCompanies ?? [],
|
||||
errorMessage: 'Unable to load companies right now.',
|
||||
deps: [cacheBust],
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
let mounted = true;
|
||||
setLoading(!cachedCompanies);
|
||||
fetchCompanies()
|
||||
.then((c) => {
|
||||
if (mounted) setCompanies(c);
|
||||
})
|
||||
.finally(() => {
|
||||
if (mounted) setLoading(false);
|
||||
});
|
||||
return () => {
|
||||
mounted = false;
|
||||
};
|
||||
}, []);
|
||||
if (!resource.error) {
|
||||
cachedCompanies = resource.data;
|
||||
}
|
||||
}, [resource.data, resource.error]);
|
||||
|
||||
return { companies, loading };
|
||||
return {
|
||||
companies: resource.data,
|
||||
loading: resource.loading,
|
||||
refreshing: resource.refreshing,
|
||||
error: resource.error,
|
||||
reload: async () => {
|
||||
invalidateCompaniesCache();
|
||||
setCacheBust((value) => value + 1);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user