This repository has been archived on 2024-11-20. You can view files and clone it, but cannot push or open issues or pull requests.
p61-project/presentation/react/contexts/HabitsTracker.tsx

62 lines
1.7 KiB
TypeScript
Raw Permalink Normal View History

2024-03-15 22:48:28 +01:00
import { createContext, useContext, useEffect } from "react"
2024-05-02 23:48:47 +02:00
import { habitsTrackerPresenter } from "@/infrastructure/instances"
2024-03-15 22:48:28 +01:00
import type {
HabitsTrackerPresenter,
HabitsTrackerPresenterState,
2024-03-16 00:36:44 +01:00
} from "@/presentation/presenters/HabitsTracker"
import { usePresenterState } from "@/presentation/react/hooks/usePresenterState"
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
}