From d6b79576407eed5287e11d3987e2e020d2248edf Mon Sep 17 00:00:00 2001 From: valentinkolb Date: Mon, 17 Jun 2024 12:10:44 +0200 Subject: [PATCH] fix(login/chat): fixed inf rerender bug there was an infinit rerender when a user was visiting the chat site while not being logged in, this was caused because functions weren't wrapped in a useCallback --- src/components/users/modals/hooks.ts | 37 ++++++++++++++++------------ src/pages/chat/ChatRouter.tsx | 6 ++++- 2 files changed, 26 insertions(+), 17 deletions(-) diff --git a/src/components/users/modals/hooks.ts b/src/components/users/modals/hooks.ts index 141dc82..f2a0185 100644 --- a/src/components/users/modals/hooks.ts +++ b/src/components/users/modals/hooks.ts @@ -1,33 +1,38 @@ import {useSearchParams} from "react-router-dom"; +import {useCallback, useMemo} from "react"; export const useSearchParamToggle = (key: string) => { - const [searchParams, setSearchParams] = useSearchParams() + const [searchParams, setSearchParams] = useSearchParams(); - const value = searchParams.get(key) === "true" + const value = searchParams.get(key) === "true"; - const open = () => { + const open = useCallback(() => { + if (value) return; setSearchParams(prev => { const newParams = new URLSearchParams(prev); - newParams.set(key, "true") - return newParams - }, {replace: true}) - } + newParams.set(key, "true"); + return newParams; + }, {replace: true}); + }, [key, value, setSearchParams]); - const close = () => { + const close = useCallback(() => { + if (!value) return; setSearchParams(prev => { const newParams = new URLSearchParams(prev); newParams.delete(key); return newParams; - }, {replace: true}) - } + }, {replace: true}); + }, [key, value, setSearchParams]); + + const toggle = useCallback(() => { + value ? close() : open(); + }, [value, close, open]); + + const handler = useMemo(() => ({open, close, toggle}), [open, close, toggle]); return { - value: value, - handler: { - open, - close, - toggle: () => value ? close() : open() - } + value, + handler } } diff --git a/src/pages/chat/ChatRouter.tsx b/src/pages/chat/ChatRouter.tsx index c2d130e..cdf5418 100644 --- a/src/pages/chat/ChatRouter.tsx +++ b/src/pages/chat/ChatRouter.tsx @@ -9,6 +9,7 @@ import ListMessagesView from "@/pages/chat/ListMessagesView.tsx"; import {usePB} from "@/lib/pocketbase.tsx"; import {useLogin} from "@/components/users/modals/hooks.ts"; import Announcements from "@/pages/chat/components/Announcements.tsx"; +import {useEffect} from "react"; const ChatIndex = () => { return
@@ -23,8 +24,11 @@ export default function ChatRouter() { const {handler} = useLogin() + useEffect(() => { + if (!user) handler.open() + }, [user]) + if (!user) { - handler.toggle() return null }