forked from scriptified/scriptified.dev
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLoadingContext.tsx
More file actions
33 lines (27 loc) · 1.11 KB
/
LoadingContext.tsx
File metadata and controls
33 lines (27 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import React, { useState } from 'react';
import { Theme, THEMES } from '../theme/theme';
import { useThemeDispatch } from '../theme/ThemeContext';
const LoadingStateContext = React.createContext(true);
const LoadingProvider = ({ children }: { children: React.ReactNode }): JSX.Element => {
const [loading, setLoading] = useState(true);
const setTheme = useThemeDispatch();
React.useEffect(() => {
setLoading(false);
// Check for theme in session storage to find the currently generated theme
// if not present set a random theme
const sessionTheme = sessionStorage.getItem('theme');
if (sessionTheme) {
setTheme(sessionTheme as Theme);
} else {
const randomTheme = THEMES[Math.floor(Math.random() * THEMES.length)];
setTheme(randomTheme);
sessionStorage.setItem('theme', randomTheme);
}
}, [setTheme]);
return <LoadingStateContext.Provider value={loading}>{children}</LoadingStateContext.Provider>;
};
const useLoadingState = (): boolean => {
const context = React.useContext(LoadingStateContext);
return context;
};
export { LoadingProvider, useLoadingState };