From dcdaa7730ab9d89d036b5d06cc6a64b26c7efdda Mon Sep 17 00:00:00 2001 From: Jake Coble Date: Mon, 16 Dec 2024 17:41:01 -0500 Subject: [PATCH] Load selected chapter after initial render --- .../organisms/passageNavigation/index.tsx | 40 ++++++++++++++----- 1 file changed, 29 insertions(+), 11 deletions(-) diff --git a/src/components/organisms/passageNavigation/index.tsx b/src/components/organisms/passageNavigation/index.tsx index 810ebc0b2..17d1f61c4 100644 --- a/src/components/organisms/passageNavigation/index.tsx +++ b/src/components/organisms/passageNavigation/index.tsx @@ -21,7 +21,7 @@ export type Version = NonNullable< GetAudiobibleIndexDataQuery['collections']['nodes'] >[0]; -type BookIndex = string | number | null; +type BookId = string | number | null; type ChapterId = string | number; type Props = { @@ -73,6 +73,20 @@ const OT = [ 'malachi', ]; +function findVersionAndBookId( + versions: Array, + chapterId: ChapterId, +): [Version, BookId] { + for (let version of versions) { + for (let book of version.sequences.nodes || []) { + if (book.recordings.nodes?.find((r) => r.id === chapterId)) { + return [version, book.id]; + } + } + } + throw Error("Couldn't find the chapter"); +} + export default function PassageNavigation({ versions, chapterId, @@ -80,25 +94,29 @@ export default function PassageNavigation({ }: Props): ReactNode { const [open, setOpen] = useState(!children); - const [selectedVersion, setSelectedVersion] = useLocalStorage( - 'bibleVersion', - versions[0], - ); + const [selectedVersion, setSelectedVersion] = useState(versions[0]); const books = selectedVersion.sequences.nodes || []; - const [selectedBookId, setSelectedBookId] = useState(books[0].id); + const [selectedBookId, setSelectedBookId] = useState(books[0].id); - const [_, setSelectedChapterId] = useLocalStorage( - 'selectedChapterId', - chapterId || null, - ); + const [selectedChapterId, setSelectedChapterId] = + useLocalStorage('selectedChapterId', chapterId || null); useEffect(() => { if (chapterId !== undefined) { setSelectedChapterId(chapterId); } - }, []); + + if (selectedChapterId !== null) { + const [version, bookId] = findVersionAndBookId( + versions, + selectedChapterId, + ); + setSelectedVersion(version); + setSelectedBookId(bookId); + } + }, [selectedChapterId]); const [selectedView, setSelectedView] = useLocalStorage<'grid' | 'list'>( 'passageNavLayout',