Skip to content

Commit

Permalink
revert: boot provider state management (#3727)
Browse files Browse the repository at this point in the history
  • Loading branch information
sshanzel authored Oct 29, 2024
1 parent 1a0ad26 commit b896afe
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 44 deletions.
10 changes: 5 additions & 5 deletions packages/shared/src/contexts/AuthContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import { AccessToken, Boot, Visit } from '../lib/boot';
import { isCompanionActivated } from '../lib/element';
import { AuthTriggers, AuthTriggersType } from '../lib/auth';
import { Squad } from '../graphql/sources';
import { checkIsExtension } from '../lib/func';
import { checkIsExtension, isNullOrUndefined } from '../lib/func';

export interface LoginState {
trigger: AuthTriggersType;
Expand Down Expand Up @@ -101,9 +101,9 @@ const logout = async (reason: string): Promise<void> => {
export type AuthContextProviderProps = {
user?: LoggedUser | AnonymousUser;
isFetched?: boolean;
isPastRegistration?: boolean;
isLegacyLogout?: boolean;
children?: ReactNode;
firstLoad?: boolean;
} & Pick<
AuthContextData,
| 'getRedirectUri'
Expand All @@ -122,7 +122,6 @@ export const AuthContextProvider = ({
user,
updateUser,
isFetched,
isPastRegistration,
loadingUser,
tokenRefreshed,
loadedUserFromCache,
Expand All @@ -132,13 +131,14 @@ export const AuthContextProvider = ({
isLegacyLogout,
accessToken,
squads,
firstLoad,
}: AuthContextProviderProps): ReactElement => {
const [loginState, setLoginState] = useState<LoginState | null>(null);
const endUser = user && 'providers' in user ? user : null;
const referral = user?.referralId || user?.referrer;
const referralOrigin = user?.referralOrigin;

if (isPastRegistration && endUser && !endUser?.infoConfirmed) {
if (firstLoad === true && endUser && !endUser?.infoConfirmed) {
logout(LogoutReason.IncomleteOnboarding);
}

Expand All @@ -149,7 +149,7 @@ export const AuthContextProvider = ({
return (
<AuthContext.Provider
value={{
isAuthReady: isFetched,
isAuthReady: !isNullOrUndefined(firstLoad),
user: endUser,
isLoggedIn: !!endUser?.id,
referral: loginState?.referral ?? referral,
Expand Down
76 changes: 37 additions & 39 deletions packages/shared/src/contexts/BootProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@ import React, {
ReactElement,
ReactNode,
useCallback,
useMemo,
useEffect,
useRef,
useState,
} from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import dynamic from 'next/dynamic';
Expand Down Expand Up @@ -109,10 +110,7 @@ export const BootDataProvider = ({
getRedirectUri,
getPage,
}: BootDataProviderProps): ReactElement => {
const { hostGranted } = useHostStatus();
const isExtension = checkIsExtension();
const queryClient = useQueryClient();

const preloadFeedsRef = useRef<PreloadFeeds>();
preloadFeedsRef.current = ({ feeds, user }) => {
if (!feeds || !user) {
Expand All @@ -130,7 +128,8 @@ export const BootDataProvider = ({
);
};

const initialData = useMemo(() => {
const [initialLoad, setInitialLoad] = useState<boolean>(null);
const [cachedBootData, setCachedBootData] = useState<Partial<Boot>>(() => {
if (localBootData) {
return localBootData;
}
Expand All @@ -148,15 +147,15 @@ export const BootDataProvider = ({
preloadFeedsRef.current({ feeds: boot.feeds, user: boot.user });

return boot;
}, [localBootData]);

const logged = initialData?.user as LoggedUser;
});
const { hostGranted } = useHostStatus();
const isExtension = checkIsExtension();
const logged = cachedBootData?.user as LoggedUser;
const shouldRefetch = !!logged?.providers && !!logged?.id;
const lastAppliedChangeRef = useRef<Partial<BootCacheData>>();
const isInitialFetch = useRef<boolean>();

const {
data: bootData,
data: remoteData,
error,
refetch,
isFetched,
Expand All @@ -167,24 +166,22 @@ export const BootDataProvider = ({
queryFn: async () => {
const result = await getBootData(app);
preloadFeedsRef.current({ feeds: result.feeds, user: result.user });
updateLocalBootData(bootData || {}, result);
isInitialFetch.current = isInitialFetch.current === undefined;

return result;
},
refetchOnWindowFocus: shouldRefetch,
staleTime: STALE_TIME,
enabled: !isExtension || !!hostGranted,
placeholderData: initialData,
});

const isBootReady = isFetched && !isError;
const loadedFromCache = !!bootData;
const { user, settings, alerts, notifications, squads } = bootData || {};
const loadedFromCache = !!cachedBootData;
const { user, settings, alerts, notifications, squads } =
cachedBootData || {};

useRefreshToken(bootData?.accessToken, refetch);
useRefreshToken(remoteData?.accessToken, refetch);
const updatedAtActive = user ? dataUpdatedAt : null;
const updateQueryCache = useCallback(
const updateBootData = useCallback(
(updatedBootData: Partial<BootCacheData>, update = true) => {
const cachedData = getCachedOrNull() || {};
const lastAppliedChange = lastAppliedChangeRef.current;
Expand All @@ -202,50 +199,51 @@ export const BootDataProvider = ({
}

const updated = updateLocalBootData(cachedData, updatedData);

queryClient.setQueryData<Partial<Boot>>(BOOT_QUERY_KEY, (previous) => {
if (!previous) {
return updated;
}

return { ...previous, ...updated };
});
setCachedBootData(updated);
},
[queryClient],
[],
);

const updateUser = useCallback(
async (newUser: LoggedUser | AnonymousUser) => {
updateQueryCache({ user: newUser });
updateBootData({ user: newUser });
await queryClient.invalidateQueries({
queryKey: generateQueryKey(RequestKey.Profile, newUser),
});
},
[updateQueryCache, queryClient],
[updateBootData, queryClient],
);

const updateSettings = useCallback(
(updatedSettings) => updateQueryCache({ settings: updatedSettings }),
[updateQueryCache],
(updatedSettings) => updateBootData({ settings: updatedSettings }),
[updateBootData],
);

const updateAlerts = useCallback(
(updatedAlerts) => updateQueryCache({ alerts: updatedAlerts }),
[updateQueryCache],
(updatedAlerts) => updateBootData({ alerts: updatedAlerts }),
[updateBootData],
);

const updateExperimentation = useCallback(
(exp: BootCacheData['exp']) => {
updateLocalBootData(bootData, { exp });
updateLocalBootData(cachedBootData, { exp });
},
[bootData],
[cachedBootData],
);

gqlClient.setHeader(
'content-language',
(user as Partial<LoggedUser>)?.language || ContentLanguage.English,
);

useEffect(() => {
if (remoteData) {
setInitialLoad(initialLoad === null);
updateBootData(remoteData);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [remoteData]);

if (error) {
return (
<div className="flex h-screen items-center justify-center">
Expand All @@ -259,7 +257,7 @@ export const BootDataProvider = ({
app={app}
user={user}
deviceId={deviceId}
experimentation={bootData?.exp}
experimentation={cachedBootData?.exp}
updateExperimentation={updateExperimentation}
>
<AuthContextProvider
Expand All @@ -269,13 +267,13 @@ export const BootDataProvider = ({
getRedirectUri={getRedirectUri}
loadingUser={!dataUpdatedAt || !user}
loadedUserFromCache={loadedFromCache}
visit={bootData?.visit}
visit={remoteData?.visit}
refetchBoot={refetch}
isFetched={isBootReady}
isLegacyLogout={bootData?.isLegacyLogout}
accessToken={bootData?.accessToken}
isPastRegistration={isInitialFetch.current}
isLegacyLogout={remoteData?.isLegacyLogout}
accessToken={remoteData?.accessToken}
squads={squads}
firstLoad={initialLoad}
>
<SettingsContextProvider
settings={settings}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ describe('useJoinReferral hook', () => {
updateUser={jest.fn()}
tokenRefreshed={false}
isFetched
firstLoad={false}
>
{children}
</AuthContextProvider>
Expand Down

0 comments on commit b896afe

Please sign in to comment.