grungnet/src/contexts/DiceLoadingContext.tsx

50 lines
1.3 KiB
TypeScript
Raw Permalink Normal View History

2021-06-03 15:31:18 +10:00
import React, { useState, useContext, ReactChild } from "react";
2021-07-16 14:55:33 +10:00
export type AssetLoadStartEventHandler = () => void;
export type AssetLoadFinishEventHandler = () => void;
2021-07-17 18:39:49 +10:00
type DiceLoadingContextValue = {
2021-07-16 14:55:33 +10:00
assetLoadStart: AssetLoadStartEventHandler;
assetLoadFinish: AssetLoadFinishEventHandler;
isLoading: boolean;
};
2021-06-03 15:31:18 +10:00
2021-07-16 14:55:33 +10:00
const DiceLoadingContext =
2021-07-17 18:39:49 +10:00
React.createContext<DiceLoadingContextValue | undefined>(undefined);
2021-06-03 15:31:18 +10:00
export function DiceLoadingProvider({ children }: { children: ReactChild }) {
const [loadingAssetCount, setLoadingAssetCount] = useState(0);
function assetLoadStart() {
setLoadingAssetCount((prevLoadingAssets) => prevLoadingAssets + 1);
}
function assetLoadFinish() {
setLoadingAssetCount((prevLoadingAssets) => prevLoadingAssets - 1);
}
const isLoading = loadingAssetCount > 0;
const value = {
assetLoadStart,
assetLoadFinish,
isLoading,
};
return (
<DiceLoadingContext.Provider value={value}>
{children}
</DiceLoadingContext.Provider>
);
}
2021-07-17 18:39:49 +10:00
export function useDiceLoading() {
const context = useContext(DiceLoadingContext);
if (context === undefined) {
throw new Error("useDiceLoading must be used within a DiceLoadingProvider");
}
return context;
}
export default DiceLoadingContext;