Skip to content

Commit

Permalink
Update settings hook usages to be more consistent
Browse files Browse the repository at this point in the history
Hopefully 401s now will not be able to propagate since the default data should be used
  • Loading branch information
thostetler committed Jan 31, 2024
1 parent 28596d4 commit 23eaf09
Show file tree
Hide file tree
Showing 12 changed files with 36 additions and 43 deletions.
6 changes: 3 additions & 3 deletions src/components/AbstractSideNav/AbstractSideNav.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { DEFAULT_USER_DATA, IDocsEntity, useGetUserSettings, useHasGraphics, useHasMetrics } from '@api';
import { IDocsEntity, useGetUserSettings, useHasGraphics, useHasMetrics } from '@api';
import { Badge } from '@chakra-ui/react';
import { IMenuItem, SideNavigationMenu, TopNavigationMenu, exportFormats } from '@components';
import { exportFormats, IMenuItem, SideNavigationMenu, TopNavigationMenu } from '@components';
import {
ArrowDownIcon as DownloadIcon,
ChartPieIcon,
Expand Down Expand Up @@ -40,7 +40,7 @@ const useGetItems = ({

// for export citation menu link, it needs to go to user's default setting if logged in
// otherwise go to bibtex
const defaultExportFormat = settings?.defaultExportFormat ?? DEFAULT_USER_DATA.defaultExportFormat;
const defaultExportFormat = settings.defaultExportFormat;
const defaultExportFormatPath =
typeof defaultExportFormat === 'string'
? values(exportFormats).find((f) => f.label === defaultExportFormat).value
Expand Down
3 changes: 2 additions & 1 deletion src/components/AbstractSources/AbstractSources.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ export interface IAbstractSourcesProps extends HTMLAttributes<HTMLDivElement> {
export const AbstractSources = ({ doc }: IAbstractSourcesProps): ReactElement => {
const isClient = useIsClient();
const { data: settings } = useGetUserSettings();
const sources = processLinkData(doc, settings?.link_server);

const sources = processLinkData(doc, settings.link_server);

const { data: relatedWorksResp } = useResolverQuery(
{ bibcode: doc.bibcode, link_type: 'associated' },
Expand Down
4 changes: 2 additions & 2 deletions src/components/AbstractSources/linkGenerator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Esources, IDocsEntity } from '@api';
import { compose, descend, is, map, pipe, prop, sort } from 'ramda';
import { DEFAULT_ORDERING, GATEWAY_BASE_URL, LINK_TYPES, MAYBE_OPEN_SOURCES } from './model';
import { getOpenUrl } from './openUrlGenerator';
import { isNilOrEmpty } from 'ramda-adjunct';
import { isNilOrEmpty, isNonEmptyString } from 'ramda-adjunct';
import { IDataProductSource, IFullTextSource, ProcessLinkDataReturns } from '@components/AbstractSources/types';

/**
Expand Down Expand Up @@ -45,7 +45,7 @@ export const processLinkData = (doc: IDocsEntity, linkServer?: string): ProcessL
*/
const maybeCreateInstitutionURL = () => {
const identifier = doc.doi || doc.issn || doc.isbn;
if (identifier && linkServer) {
if (identifier && isNonEmptyString(linkServer)) {
return {
url: getOpenUrl({ metadata: doc, linkServer }),
openUrl: true,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export interface ICustomFormatSelectProps {
export const CustomFormatSelect = ({ dispatch }: ICustomFormatSelectProps) => {
const { isAuthenticated } = useSession();

const { settings: settingsData } = useSettings({ enabled: isAuthenticated, suspense: false });
const { settings: settingsData } = useSettings({ suspense: false });

const customFormats = settingsData?.customFormats ?? DEFAULT_USER_DATA.customFormats;

Expand Down
11 changes: 3 additions & 8 deletions src/components/ResultList/ListActions.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Bibcode, DEFAULT_USER_DATA, ExportApiFormatKey, useVaultBigQuerySearch } from '@api';
import { Bibcode, ExportApiFormatKey, useVaultBigQuerySearch } from '@api';
import { ChevronDownIcon, SettingsIcon } from '@chakra-ui/icons';
import {
Button,
Expand Down Expand Up @@ -56,9 +56,7 @@ export const ListActions = (props: IListActionsProps): ReactElement => {
const router = useRouter();
const toast = useToast();

const { settings } = useSettings({
enabled: isAuthenticated,
});
const { settings } = useSettings({ suspense: false });

useEffect(() => {
setExploreAll(noneSelected);
Expand Down Expand Up @@ -187,10 +185,7 @@ export const ListActions = (props: IListActionsProps): ReactElement => {
<MenuDivider />
</>
)}
<ExportMenu
exploreAll={exploreAll}
defaultExportFormat={settings?.defaultExportFormat ?? DEFAULT_USER_DATA.defaultExportFormat}
/>
<ExportMenu exploreAll={exploreAll} defaultExportFormat={settings.defaultExportFormat} />
<OrcidBulkMenu />
</MenuList>
</Portal>
Expand Down
21 changes: 8 additions & 13 deletions src/lib/useSession.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,17 @@
import api, { isAuthenticated } from '@api';
import axios from 'axios';
import { useEffect } from 'react';
import { NotificationId } from '@store/slices';
import { useUser } from '@lib/useUser';
import { useMutation } from '@tanstack/react-query';
import { ILogoutResponse } from '@pages/api/auth/logout';
import { useReloadWithNotification } from '@components/Notification';

interface IUseSessionProps {
redirectWithMessage?: NotificationId;
}
import { useRouter } from 'next/router';

/**
* Provides access to the user session and methods to logout
* @param props
*/
export const useSession = (props: IUseSessionProps = { redirectWithMessage: null }) => {
const { redirectWithMessage } = props;
export const useSession = () => {
const { user, reset } = useUser();
const reload = useReloadWithNotification();
const { reload } = useRouter();

const { mutate: logout, ...result } = useMutation(['logout'], async () => {
const { data } = await axios.post<ILogoutResponse>('/api/auth/logout');
Expand All @@ -28,13 +21,15 @@ export const useSession = (props: IUseSessionProps = { redirectWithMessage: null
useEffect(() => {
if (result.data?.success) {
api.reset();
reset().finally(() => void reload(redirectWithMessage ?? 'account-logout-success'));
reset().finally(() => {
reload();
});
}
}, [result.data?.success, redirectWithMessage]);
}, [result.data?.success]);

useEffect(() => {
if (result.isError) {
void reload('account-logout-failed');
reload();
}
}, [result.isError]);

Expand Down
4 changes: 4 additions & 0 deletions src/lib/useSettings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,10 @@ import { useQueryClient, UseQueryOptions } from '@tanstack/react-query';
import { useToast } from '@chakra-ui/react';
import { useEffect } from 'react';
import { isNotEmpty } from 'ramda-adjunct';
import { useSession } from '@lib/useSession';

export const useSettings = (options?: UseQueryOptions<IADSApiUserDataResponse>) => {
const { isAuthenticated } = useSession();
const toast = useToast({
position: 'bottom',
isClosable: true,
Expand All @@ -23,6 +25,8 @@ export const useSettings = (options?: UseQueryOptions<IADSApiUserDataResponse>)
const queryClient = useQueryClient();
const { data: settings, ...getSettingsState } = useGetUserSettings({
suspense: true,
retry: false,
enabled: isAuthenticated,
...options,
});
const { mutate, ...updateSettingsState } = useUpdateUserSettings({
Expand Down
8 changes: 6 additions & 2 deletions src/pages/_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,11 @@ import dynamic from 'next/dynamic';
import { useRouter } from 'next/router';
import 'nprogress/nprogress.css';
import { FC, memo, ReactElement, useEffect } from 'react';
import { DehydratedState, Hydrate, QueryClientProvider, useQuery } from '@tanstack/react-query';
import { DehydratedState, Hydrate, QueryClientProvider, useQuery, useQueryClient } from '@tanstack/react-query';
import { ReactQueryDevtools } from '@tanstack/react-query-devtools';
import { IronSession } from 'iron-session';
import axios from 'axios';
import api, { checkUserData } from '@api';
import api, { checkUserData, userKeys } from '@api';
import { isNilOrEmpty, notEqual } from 'ramda-adjunct';
import { useUser } from '@lib/useUser';
import { GoogleReCaptchaProvider } from 'react-google-recaptcha-v3';
Expand Down Expand Up @@ -106,6 +106,7 @@ const UserSync = (): ReactElement => {
const router = useRouter();
const store = useStoreApi();
const { user } = useUser();
const qc = useQueryClient();

const { data } = useQuery<{
user: IronSession['token'];
Expand All @@ -132,6 +133,9 @@ const UserSync = (): ReactElement => {

// apply the user data to the api instance
api.setUserData(data.user);

// attempt to invalidate any currently cached user settings
void qc.invalidateQueries(userKeys.getUserSettings());
}
}, [data, store, user]);

Expand Down
4 changes: 0 additions & 4 deletions src/pages/abs/[id]/exportcitation/[format].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import { path } from 'ramda';
import { composeNextGSSP } from '@ssr-utils';
import { useRouter } from 'next/router';
import { getDetailsPageTitle } from '@pages/abs/[id]/abstract';
import { useSession } from '@lib/useSession';
import { useSettings } from '@lib/useSettings';

const ExportCitationPage: NextPage = () => {
Expand All @@ -18,11 +17,8 @@ const ExportCitationPage: NextPage = () => {
const { data } = useGetAbstract({ id: router.query.id as string });
const doc = path<IDocsEntity>(['docs', 0], data);

const { isAuthenticated } = useSession();

// get export related user settings
const { settings } = useSettings({
enabled: isAuthenticated,
suspense: false,
});

Expand Down
3 changes: 0 additions & 3 deletions src/pages/search/exportcitation/[format].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ import { useRouter } from 'next/router';
import { last, omit } from 'ramda';
import { dehydrate, QueryClient } from '@tanstack/react-query';
import { composeNextGSSP } from '@ssr-utils';
import { useSession } from '@lib/useSession';
import { useSettings } from '@lib/useSettings';

interface IExportCitationPageProps {
Expand All @@ -39,11 +38,9 @@ const ExportCitationPage: NextPage<IExportCitationPageProps> = (props) => {
const { format, query, error } = props;
const isClient = useIsClient();
const router = useRouter();
const { isAuthenticated } = useSession();

// get export related user settings
const { settings } = useSettings({
enabled: isAuthenticated,
suspense: false,
});

Expand Down
11 changes: 6 additions & 5 deletions src/pages/user/account/login.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,17 @@ import { FormEventHandler, useCallback, useEffect, useState } from 'react';
import { useMutation } from '@tanstack/react-query';
import axios, { AxiosError } from 'axios';
import { ILoginResponse } from '@pages/api/auth/login';
import { useReloadWithNotification } from '@components/Notification';
import { useFocus } from '@lib/useFocus';
import { useUser } from '@lib/useUser';
import { parseAPIError } from '@utils';
import { useRouter } from 'next/router';

const initialParams: IUserCredentials = { email: '', password: '' };

const Login: NextPage = () => {
const { reload } = useRouter();
const [params, setParams] = useState<IUserCredentials>(initialParams);
const [mainInputRef, focus] = useFocus<HTMLInputElement>();
const reload = useReloadWithNotification();
const { reset: resetUser } = useUser();

const {
Expand All @@ -44,7 +44,7 @@ const Login: NextPage = () => {
// redirect on successful login
useEffect(() => {
if (data?.success) {
resetUser().finally(() => void reload('account-login-success'));
reload();
}
}, [data?.success, reload, resetUser]);

Expand Down Expand Up @@ -108,10 +108,11 @@ const Login: NextPage = () => {
<SimpleLink alignSelf="flex-end" href="/user/account/forgotpassword">
Forgot password?
</SimpleLink>
<Button type="submit" isLoading={isLoading}>
{/* show loading indicator even after success, since we should be awaiting a page refresh */}
<Button type="submit" isLoading={isLoading || data?.success}>
Submit
</Button>
{isLoading ? null : (
{isLoading || data?.success ? null : (
<SimpleLink alignSelf="center" href="/user/account/register">
Register
</SimpleLink>
Expand Down
2 changes: 1 addition & 1 deletion src/pages/user/settings/delete.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ const DeleteAccountPage = () => {
const [email, setEmail] = useState('');
const [formError, setFormError] = useState<FormError>(null);
const storeEmail = useStore((state: AppState) => state.user.username);
const { logout } = useSession({ redirectWithMessage: 'account-deleted-success' });
const { logout } = useSession();
const {
mutate: deleteAccount,
error,
Expand Down

0 comments on commit 23eaf09

Please sign in to comment.