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

62 lines
1.7 KiB
TypeScript
Raw Normal View History

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