|
| 1 | +import React, { useContext } from 'react'; |
| 2 | +import type { SeasonStatusState } from '../../../app/scripts/controllers/rewards/rewards-controller.types'; |
| 3 | +import { useCandidateSubscriptionId } from '../../hooks/rewards/useCandidateSubscriptionId'; |
| 4 | +import { useSeasonStatus } from '../../hooks/rewards/useSeasonStatus'; |
| 5 | +import { useRewardsEnabled } from '../../hooks/rewards/useRewardsEnabled'; |
| 6 | + |
| 7 | +export interface RewardsContextValue { |
| 8 | + rewardsEnabled: boolean; |
| 9 | + candidateSubscriptionId: string | null; |
| 10 | + candidateSubscriptionIdError: boolean; |
| 11 | + seasonStatus: SeasonStatusState | null; |
| 12 | + seasonStatusError: string | null; |
| 13 | + seasonStatusLoading: boolean; |
| 14 | + refetchSeasonStatus: () => Promise<void>; |
| 15 | +} |
| 16 | + |
| 17 | +export const RewardsContext = React.createContext<RewardsContextValue>({ |
| 18 | + rewardsEnabled: false, |
| 19 | + candidateSubscriptionId: null, |
| 20 | + candidateSubscriptionIdError: false, |
| 21 | + seasonStatus: null, |
| 22 | + seasonStatusError: null, |
| 23 | + seasonStatusLoading: false, |
| 24 | + refetchSeasonStatus: async () => { |
| 25 | + // Default empty function |
| 26 | + }, |
| 27 | +}); |
| 28 | + |
| 29 | +export const useRewardsContext = () => { |
| 30 | + const context = useContext(RewardsContext); |
| 31 | + if (!context) { |
| 32 | + throw new Error('useRewardsContext must be used within a RewardsProvider'); |
| 33 | + } |
| 34 | + return context; |
| 35 | +}; |
| 36 | + |
| 37 | +export const RewardsProvider: React.FC = ({ children }) => { |
| 38 | + const rewardsEnabled = useRewardsEnabled(); |
| 39 | + const { |
| 40 | + candidateSubscriptionId, |
| 41 | + candidateSubscriptionIdError, |
| 42 | + fetchCandidateSubscriptionId, |
| 43 | + } = useCandidateSubscriptionId(); |
| 44 | + |
| 45 | + const { |
| 46 | + seasonStatus, |
| 47 | + seasonStatusError, |
| 48 | + seasonStatusLoading, |
| 49 | + fetchSeasonStatus, |
| 50 | + } = useSeasonStatus({ |
| 51 | + subscriptionId: candidateSubscriptionId, |
| 52 | + onAuthorizationError: fetchCandidateSubscriptionId, |
| 53 | + }); |
| 54 | + |
| 55 | + return ( |
| 56 | + <RewardsContext.Provider |
| 57 | + value={{ |
| 58 | + rewardsEnabled, |
| 59 | + candidateSubscriptionId, |
| 60 | + candidateSubscriptionIdError, |
| 61 | + seasonStatus, |
| 62 | + seasonStatusError, |
| 63 | + seasonStatusLoading, |
| 64 | + refetchSeasonStatus: fetchSeasonStatus, |
| 65 | + }} |
| 66 | + > |
| 67 | + {children} |
| 68 | + </RewardsContext.Provider> |
| 69 | + ); |
| 70 | +}; |
0 commit comments