First Commit
This commit is contained in:
@@ -0,0 +1,50 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { api } from "../api";
|
||||
import { Company } from "../types";
|
||||
|
||||
let cachedCompanies: Company[] | null = null;
|
||||
let inflight: Promise<Company[]> | null = null;
|
||||
|
||||
async function fetchCompanies(): Promise<Company[]> {
|
||||
if (cachedCompanies) return cachedCompanies;
|
||||
if (inflight) return inflight;
|
||||
|
||||
inflight = api
|
||||
.get<Company[]>("/companies")
|
||||
.then((r) => {
|
||||
cachedCompanies = r.data;
|
||||
return r.data;
|
||||
})
|
||||
.finally(() => {
|
||||
inflight = null;
|
||||
});
|
||||
|
||||
return inflight;
|
||||
}
|
||||
|
||||
export function invalidateCompaniesCache() {
|
||||
cachedCompanies = null;
|
||||
}
|
||||
|
||||
export function useCompanies() {
|
||||
const [companies, setCompanies] = useState<Company[]>(cachedCompanies ?? []);
|
||||
const [loading, setLoading] = useState(!cachedCompanies);
|
||||
|
||||
useEffect(() => {
|
||||
let mounted = true;
|
||||
setLoading(!cachedCompanies);
|
||||
fetchCompanies()
|
||||
.then((c) => {
|
||||
if (mounted) setCompanies(c);
|
||||
})
|
||||
.finally(() => {
|
||||
if (mounted) setLoading(false);
|
||||
});
|
||||
return () => {
|
||||
mounted = false;
|
||||
};
|
||||
}, []);
|
||||
|
||||
return { companies, loading };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
export function useDebouncedValue<T>(value: T, delayMs: number): T {
|
||||
const [debounced, setDebounced] = useState<T>(value);
|
||||
|
||||
useEffect(() => {
|
||||
const t = window.setTimeout(() => setDebounced(value), delayMs);
|
||||
return () => window.clearTimeout(t);
|
||||
}, [value, delayMs]);
|
||||
|
||||
return debounced;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user