Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(organizations): add of useSession hook TASK-1305 #5303

Merged
merged 3 commits into from
Nov 27, 2024
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 mob-x 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),
};

};