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"
|
|
|
|
import { habitsTrackerPresenter } from "@/infrastructure"
|
2024-03-22 23:41:51 +01:00
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2024-03-22 23:41:51 +01:00
|
|
|
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
|
|
|
|
|
2024-03-22 23:41:51 +01:00
|
|
|
const { user } = useAuthentication()
|
|
|
|
|
2024-03-15 22:48:28 +01:00
|
|
|
useEffect(() => {
|
2024-03-22 23:41:51 +01:00
|
|
|
if (user == null) {
|
|
|
|
return
|
|
|
|
}
|
2024-03-15 22:48:28 +01:00
|
|
|
habitsTrackerPresenter
|
2024-03-22 23:41:51 +01:00
|
|
|
.retrieveHabitsTracker({ userId: user.id })
|
2024-03-15 22:48:28 +01:00
|
|
|
.catch((error) => {
|
|
|
|
console.error(error)
|
|
|
|
})
|
2024-03-22 23:41:51 +01:00
|
|
|
}, [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)
|
2024-03-22 23:41:51 +01:00
|
|
|
if (context === defaultContextValue) {
|
2024-03-15 22:48:28 +01:00
|
|
|
throw new Error(
|
|
|
|
"`useHabitsTracker` must be used within a `HabitsTrackerProvider`.",
|
|
|
|
)
|
|
|
|
}
|
|
|
|
return context
|
|
|
|
}
|