From 2f609b7ec091e53c8b966f081a36e8b4c6241f0b Mon Sep 17 00:00:00 2001 From: Marco Lipparini Date: Thu, 28 Mar 2024 00:37:49 +0100 Subject: [PATCH] Adding an option to enable auto-logout when the wallet is disconnected --- src/components/Web3RouteGuard.tsx | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/src/components/Web3RouteGuard.tsx b/src/components/Web3RouteGuard.tsx index a4617d0..4d44704 100644 --- a/src/components/Web3RouteGuard.tsx +++ b/src/components/Web3RouteGuard.tsx @@ -1,5 +1,6 @@ import { usePathname, useRouter, useSearchParams } from 'next/navigation'; -import { useEffect, PropsWithChildren, ReactNode } from 'react'; +import { useEffect, PropsWithChildren, ReactNode, useCallback } from 'react'; +import { useAccountEffect } from 'wagmi'; import { useWeb3AuthToken } from '../hooks/useWeb3AuthToken'; @@ -8,6 +9,7 @@ type Web3RouteGuardProps = { loginSearchParams?: string[][]; token: Parameters[0]; fallback?: ReactNode | undefined; + logoutOnDisconnect?: boolean; }; export const Web3RouteGuard = ({ @@ -15,14 +17,25 @@ export const Web3RouteGuard = ({ loginSearchParams = [], token: tokenOptions, fallback, + logoutOnDisconnect = false, children, }: PropsWithChildren) => { const router = useRouter(); const pathname = usePathname(); const searchParams = useSearchParams(); - const { isVerifying, isAuthenticated } = useWeb3AuthToken(tokenOptions); + const { isVerifying, isAuthenticated, clear } = useWeb3AuthToken(tokenOptions); const currentUrl = `${pathname}?${searchParams}`; + useAccountEffect({ + onDisconnect: useCallback(() => { + if (!logoutOnDisconnect) { + return; + } + + clear(); + }, [logoutOnDisconnect, clear]), + }); + useEffect(() => { if (isAuthenticated || isVerifying) { return;