Im building a React JS with Typescript web application with Context to store the user details. I have implemented the Google SSO and thereafter Im setting the user object in the context. In the first try when I complete the sign in process and navigate to home, the context values are displayed correctly, but when i click on any of the options in the menu bar and navigate to a different page the context resets to the default value.
Below attached is the code base
RouteComponent.tsx
const router = createBrowserRouter([
{
element: <CustomeLayout />,
children: [
{
path: `${ROUTES.HOMEPAGEROUTE}`,
element: <HomePage />,
errorElement: <NotFoundPage />
},
{
path: `${ROUTES.SERVICESPAGEROUTE}`,
element: <ServicesPage />
},
{
path: `${ROUTES.ABOUTUSPAGE}`,
element: <AboutusPage />
}
]
}
]);
export default function RouteComponent() {
return (
<RouterProvider router={router} />
)
}
AuthContext.tsx
export const AuthContextProvider: React.FC<LayoutType> = ({ children }) => {
const [user, setUser] = useState<UserType | null>(null);
//common functionality to set the user details
const setUserDetails = (data: any) => {
const currentUser: UserType = {
firstName: data.displayName.split(" ")[0],
lastName: data.displayName.split(" ")[1],
mobileNumber: data.phoneNumber,
emailAddress: data.email,
isMFAEnabled: data.phoneNumber ? true : false
};
setUser(currentUser)
};
//Google SSO login function
const ssoSignIn = async (): Promise<boolean> => {
try {
const response = await ssoSignInFunc();
if (!response) throw new Error("Unable to complete SSO login");
setUserDetails(response.user);
localStorage.setItem('Token', response.user.accessToken);
return true;
} catch (error) {
const err = error as AxiosError;
throw new Error(err.message);
}
};
const contextValue: AuthContextType = useMemo(() => {
return {
ssoSignIn,
user
}
}, [user]);
return (
<AuthContext.Provider value={contextValue}>
{children}
</AuthContext.Provider>
)
}
App.tsx
function App() {
return (
<AuthContextProvider>
<RouteComponent />
</AuthContextProvider>
);
}
Once the login is completed the user is navigated to the home page
Login.tsx
const {ssoSignIn} = useContext(AuthContext);
const navigate = useNavigate();
const loginUser = async () => {
try {
const response = await ssoSignIn();
if(!response) setError("Error in Signing in user");
navigate(ROUTES.HOMEPAGEROUTE);
} catch (error) {
setError("Error in Signing in user");
}
}
I want to keep the user object persisted throughout the application once the value is set.
Jeshreen is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.