1
1
mirror of https://github.com/theoludwig/p61-project.git synced 2024-07-17 07:00:12 +02:00
p61-project/contexts/HabitsTracker.tsx

55 lines
1.5 KiB
TypeScript
Raw Normal View History

2024-03-15 22:48:28 +01:00
import { createContext, useContext, useEffect } from "react"
import type {
HabitsTrackerPresenter,
HabitsTrackerPresenterState,
} from "@/data/infrastructure/presenters/HabitsTrackerPresenter"
import { usePresenterState } from "@/hooks/usePresenterState"
import { habitsTrackerPresenter } from "@/data/infrastructure"
export interface HabitsTrackerContextValue {
habitsTrackerPresenterState: HabitsTrackerPresenterState
habitsTrackerPresenter: HabitsTrackerPresenter
}
const defaultHabitsTrackerContextValue = {} as HabitsTrackerContextValue
const HabitsTrackerContext = createContext<HabitsTrackerContextValue>(
defaultHabitsTrackerContextValue,
)
interface HabitsTrackerProviderProps extends React.PropsWithChildren {}
export const HabitsTrackerProvider: React.FC<HabitsTrackerProviderProps> = (
props,
) => {
const { children } = props
useEffect(() => {
habitsTrackerPresenter
.retrieveHabitsTracker({ userId: "1" })
.catch((error) => {
console.error(error)
})
}, [])
const habitsTrackerPresenterState = usePresenterState(habitsTrackerPresenter)
return (
<HabitsTrackerContext.Provider
value={{ habitsTrackerPresenterState, habitsTrackerPresenter }}
>
{children}
</HabitsTrackerContext.Provider>
)
}
export const useHabitsTracker = (): HabitsTrackerContextValue => {
const context = useContext(HabitsTrackerContext)
if (context === defaultHabitsTrackerContextValue) {
throw new Error(
"`useHabitsTracker` must be used within a `HabitsTrackerProvider`.",
)
}
return context
}