Skip to content

Commit

Permalink
Reapply "refactor(organizations): add of useSession hook TASK-1305 (#…
Browse files Browse the repository at this point in the history
…5303)"

This reverts commit 6c3e3af.
  • Loading branch information
RuthShryock committed Dec 2, 2024
1 parent cd35d96 commit 039063b
Showing 1 changed file with 49 additions and 0 deletions.
49 changes: 49 additions & 0 deletions jsapp/js/stores/useSession.tsx
Original file line number Diff line number Diff line change
@@ -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<AccountResponse>();
const [isAnonymous, setIsAnonymous] = useState<boolean>(true);
const [isPending, setIsPending] = useState<boolean>(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),
};
};

0 comments on commit 039063b

Please sign in to comment.