From 039063b26b9e4c32e5ff4cc8f0a06dfbb3d2f4dd Mon Sep 17 00:00:00 2001 From: RuthShryock Date: Mon, 2 Dec 2024 14:26:40 -0500 Subject: [PATCH] Reapply "refactor(organizations): add of useSession hook TASK-1305 (#5303)" This reverts commit 6c3e3af5029b28dcecf35255fa844262116e9ebb. --- jsapp/js/stores/useSession.tsx | 49 ++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 jsapp/js/stores/useSession.tsx diff --git a/jsapp/js/stores/useSession.tsx b/jsapp/js/stores/useSession.tsx new file mode 100644 index 0000000000..59531767f5 --- /dev/null +++ b/jsapp/js/stores/useSession.tsx @@ -0,0 +1,49 @@ +import sessionStore from './session'; +import {useEffect, useState} from 'react'; +import {reaction} from 'mobx'; +import type {AccountResponse} from '../dataInterface'; + +/** + * Hook to use the session store in functional components. + * This hook provides a way to access teh current logged account, information + * regarding the anonymous state of the login and session methods. + * + * This hook uses MobX reactions to track the current account and update the + * state accordingly. + * In the future we should update this hook to use react-query and drop the usage of mob-x + */ +export const useSession = () => { + const [currentLoggedAccount, setCurrentLoggedAccount] = + useState(); + const [isAnonymous, setIsAnonymous] = useState(true); + const [isPending, setIsPending] = useState(false); + + useEffect(() => { + // We need to setup a reaction for every observable we want to track + // Generic reaction to sessionStore won't fire the re-rendering of the hook + const currentAccountReactionDisposer = reaction( + () => sessionStore.currentAccount, + (currentAccount) => { + if (sessionStore.isLoggedIn) { + setCurrentLoggedAccount(currentAccount as AccountResponse); + setIsAnonymous(false); + setIsPending(sessionStore.isPending); + } + }, + {fireImmediately: true} + ); + + return () => { + currentAccountReactionDisposer(); + }; + }, []); + + return { + currentLoggedAccount, + isAnonymous, + isPending, + logOut: sessionStore.logOut.bind(sessionStore), + logOutAll: sessionStore.logOutAll.bind(sessionStore), + refreshAccount: sessionStore.refreshAccount.bind(sessionStore), + }; +};