From a5b9ed777166425d216db3d1c589e44b9bce5be1 Mon Sep 17 00:00:00 2001 From: WithoutPants <53250216+WithoutPants@users.noreply.github.com> Date: Sun, 24 Sep 2023 13:41:18 +1000 Subject: [PATCH] Improve lightbox context hook --- ui/v2.5/src/hooks/Lightbox/context.tsx | 19 +++++++++++++++---- ui/v2.5/src/hooks/Lightbox/hooks.ts | 8 ++++---- 2 files changed, 19 insertions(+), 8 deletions(-) diff --git a/ui/v2.5/src/hooks/Lightbox/context.tsx b/ui/v2.5/src/hooks/Lightbox/context.tsx index b44a1127d83..8bae11cffe1 100644 --- a/ui/v2.5/src/hooks/Lightbox/context.tsx +++ b/ui/v2.5/src/hooks/Lightbox/context.tsx @@ -19,12 +19,21 @@ export interface IState { onClose?: () => void; } interface IContext { + lightboxState: IState; setLightboxState: (state: Partial) => void; } -export const LightboxContext = React.createContext({ - setLightboxState: () => {}, -}); +export const LightboxContext = React.createContext(null); + +export function useLightboxContext() { + const context = React.useContext(LightboxContext); + if (!context) { + throw new Error( + "useLightboxContext must be used within a LightboxProvider" + ); + } + return context; +} export const LightboxProvider: React.FC = ({ children }) => { const [lightboxState, setLightboxState] = useState({ @@ -53,7 +62,9 @@ export const LightboxProvider: React.FC = ({ children }) => { }; return ( - + {children} }> {lightboxState.isVisible && ( diff --git a/ui/v2.5/src/hooks/Lightbox/hooks.ts b/ui/v2.5/src/hooks/Lightbox/hooks.ts index 8ec511f52e2..a54de4c3095 100644 --- a/ui/v2.5/src/hooks/Lightbox/hooks.ts +++ b/ui/v2.5/src/hooks/Lightbox/hooks.ts @@ -1,13 +1,13 @@ -import { useCallback, useContext, useEffect, useMemo, useState } from "react"; +import { useCallback, useEffect, useMemo, useState } from "react"; import * as GQL from "src/core/generated-graphql"; -import { LightboxContext, IState } from "./context"; +import { IState, useLightboxContext } from "./context"; import { IChapter } from "./types"; export const useLightbox = ( state: Partial>, chapters: IChapter[] = [] ) => { - const { setLightboxState } = useContext(LightboxContext); + const { setLightboxState } = useLightboxContext(); useEffect(() => { setLightboxState({ @@ -50,7 +50,7 @@ export const useLightbox = ( }; export const useGalleryLightbox = (id: string, chapters: IChapter[] = []) => { - const { setLightboxState } = useContext(LightboxContext); + const { setLightboxState } = useLightboxContext(); const pageSize = 40; const [page, setPage] = useState(1);