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
This commit is contained in:
Valentin Kolb 2024-06-17 12:10:44 +02:00
parent 6a88c1b516
commit d6b7957640
2 changed files with 26 additions and 17 deletions

View File

@ -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
}
}

View File

@ -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 <Center>
@ -23,8 +24,11 @@ export default function ChatRouter() {
const {handler} = useLogin()
useEffect(() => {
if (!user) handler.open()
}, [user])
if (!user) {
handler.toggle()
return null
}