|
1
|
import React from "react" |
|
2
|
import { createContext, useContext, useState } from "react" |
|
3
|
|
|
4
|
type LoadingContextType = { |
|
5
|
loading: boolean |
|
6
|
removeLoading: () => void |
|
7
|
} |
|
8
|
|
|
9
|
const LoadingContext = createContext<LoadingContextType | null>(null) |
|
10
|
|
|
11
|
type LoadingProviderProps = { |
|
12
|
children: React.ReactNode |
|
13
|
initialLoading?: boolean |
|
14
|
} |
|
15
|
|
|
16
|
const LoadingProvider = ({ |
|
17
|
children, |
|
18
|
initialLoading = false, |
|
19
|
}: LoadingProviderProps) => { |
|
20
|
const [loading, setLoading] = useState<boolean>(initialLoading) |
|
21
|
|
|
22
|
const removeLoading = () => setLoading(false) |
|
23
|
|
|
24
|
return ( |
|
25
|
<LoadingContext.Provider |
|
26
|
value={{ |
|
27
|
loading, |
|
28
|
removeLoading, |
|
29
|
}} |
|
30
|
> |
|
31
|
{children} |
|
32
|
</LoadingContext.Provider> |
|
33
|
) |
|
34
|
} |
|
35
|
|
|
36
|
export default LoadingProvider |
|
37
|
|
|
38
|
export const useLoading = (): LoadingContextType => { |
|
39
|
const context = useContext(LoadingContext) |
|
40
|
|
|
41
|
if (!context) { |
|
42
|
throw new Error("useLoading must be used inside a LoadingProvider") |
|
43
|
} |
|
44
|
|
|
45
|
return context |
|
46
|
} |