74 lines
2.3 KiB
JavaScript
74 lines
2.3 KiB
JavaScript
import React, { createContext, useContext, useState, useEffect } from 'react';
|
|
import { API_CONFIG } from '../constants/api';
|
|
|
|
const BaseEnumsContext = createContext({ enums: null, refresh: () => {}, getEnums: async () => null });
|
|
|
|
export const BaseEnumsProvider = ({ children }) => {
|
|
const [enums, setEnums] = useState(null);
|
|
const [lastFetched, setLastFetched] = useState(0);
|
|
const [branchesByRegion, setBranchesByRegion] = useState({});
|
|
const [branchesFetchedAt, setBranchesFetchedAt] = useState(0);
|
|
|
|
const fetchEnums = async () => {
|
|
try {
|
|
const res = await fetch(`${API_CONFIG.BASE_URL}${API_CONFIG.ENDPOINTS.ENUMS}`);
|
|
const json = await res.json();
|
|
setEnums(json);
|
|
setLastFetched(Date.now());
|
|
} catch (e) {
|
|
console.warn('Failed to fetch base-app-enums', e.message);
|
|
}
|
|
};
|
|
|
|
const fetchBranches = async () => {
|
|
try {
|
|
const res = await fetch(`${API_CONFIG.BASE_URL}/branches?groupBy=region`);
|
|
const json = await res.json();
|
|
setBranchesByRegion(json || {});
|
|
setBranchesFetchedAt(Date.now());
|
|
} catch (e) {
|
|
console.warn('Failed to fetch branches', e.message);
|
|
}
|
|
};
|
|
|
|
// initial fetch and 60s refresh
|
|
useEffect(() => {
|
|
fetchEnums();
|
|
fetchBranches();
|
|
const id = setInterval(fetchEnums, 60000);
|
|
const idB = setInterval(fetchBranches, 60000);
|
|
return () => { clearInterval(id); clearInterval(idB);} ;
|
|
}, []);
|
|
|
|
const getEnums = async () => {
|
|
if (!enums || Date.now() - lastFetched > 60000) {
|
|
await fetchEnums();
|
|
}
|
|
return enums;
|
|
};
|
|
|
|
const getLabel = (category, key) => {
|
|
if (!enums || !enums[category]) return key;
|
|
return enums[category][key] ?? key;
|
|
};
|
|
|
|
const getOptions = (category) => {
|
|
if (!enums || !enums[category]) return [];
|
|
return Object.entries(enums[category]).map(([value, label]) => ({ value, label }));
|
|
};
|
|
|
|
const getBranches = async (regionKey) => {
|
|
if (Date.now() - branchesFetchedAt > 60000) {
|
|
await fetchBranches();
|
|
}
|
|
return regionKey ? branchesByRegion[regionKey] || [] : [];
|
|
};
|
|
|
|
return (
|
|
<BaseEnumsContext.Provider value={{ enums, refresh: fetchEnums, getEnums, getLabel, getOptions, getBranches }}>
|
|
{children}
|
|
</BaseEnumsContext.Provider>
|
|
);
|
|
};
|
|
|
|
export const useBaseEnums = () => useContext(BaseEnumsContext);
|