Skip to content

Commit

Permalink
Fix react-query cache persistence (#18762)
Browse files Browse the repository at this point in the history
* adjust when we clear query cache

* adjusting icon/color

* remove log statement

* strip off protocol

* shifting query client clear() for unauthenticated users
  • Loading branch information
selfcontained authored Sep 21, 2023
1 parent d7ba4db commit b02c94d
Show file tree
Hide file tree
Showing 7 changed files with 64 additions and 54 deletions.
2 changes: 1 addition & 1 deletion components/dashboard/src/Login.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export const Login: FC<LoginProps> = ({ onLoggedIn }) => {

const updateUser = useCallback(async () => {
await getGitpodService().reconnect();
const [user] = await Promise.all([getGitpodService().server.getLoggedInUser()]);
const user = await getGitpodService().server.getLoggedInUser();
setUser(user);
markLoggedIn();
}, [setUser]);
Expand Down
16 changes: 3 additions & 13 deletions components/dashboard/src/components/RepositoryFinder.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import { ReactComponent as RepositoryIcon } from "../icons/RepositoryWithColor.s
import { useSuggestedRepositories } from "../data/git-providers/suggested-repositories-query";
import { useFeatureFlag } from "../data/featureflag-query";
import { SuggestedRepository } from "@gitpod/gitpod-protocol";
import classNames from "classnames";
import { MiddleDot } from "./typography/MiddleDot";

// TODO: Remove this once we've fully enabled `includeProjectsOnCreateWorkspace`
Expand Down Expand Up @@ -157,14 +156,7 @@ export default function RepositoryFinder(props: RepositoryFinderProps) {
searchPlaceholder="Paste repository URL or type to find suggestions"
>
<DropDown2SelectedElement
// TODO: clean this up - have to use different icons to keep the right shade of gray when there's no project
icon={
selectedSuggestion?.projectId ? (
<RepositoryIcon className={classNames("w-8 h-8 text-orange-500")} />
) : (
RepositorySVG
)
}
icon={RepositorySVG}
htmlTitle={displayContextUrl(props.selectedContextURL) || "Repository"}
title={
<div className="truncate w-80">
Expand All @@ -178,7 +170,7 @@ export default function RepositoryFinder(props: RepositoryFinderProps) {
subtitle={
// Only show the url if we have a project or repo name, otherwise it's redundant w/ the title
selectedSuggestion?.projectName || selectedSuggestion?.repositoryName
? selectedSuggestion?.url
? displayContextUrl(selectedSuggestion?.url)
: undefined
}
loading={props.loading || isLoading}
Expand All @@ -199,9 +191,7 @@ const SuggestedRepositoryOption: FC<SuggestedRepositoryOptionProps> = ({ repo })
aria-label={`${repo.projectId ? "Project" : "Repo"}: ${repo.url}`}
>
<span className={"pr-2"}>
<RepositoryIcon
className={classNames("w-5 h-5 text-orange-500", !repo.projectId && "filter-grayscale")}
/>
<RepositoryIcon className={"w-5 h-5 text-gray-400"} />
</span>

{name && (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
*/

import { ErrorCodes } from "@gitpod/gitpod-protocol/lib/messaging/error";
import { QueryErrorResetBoundary } from "@tanstack/react-query";
import { QueryErrorResetBoundary, useQueryClient } from "@tanstack/react-query";
import { FC } from "react";
import { ErrorBoundary, FallbackProps } from "react-error-boundary";
import { hasLoggedInBefore, Login } from "../../Login";
Expand All @@ -28,11 +28,14 @@ export const QueryErrorBoundary: FC = ({ children }) => {

// This handles any expected errors, i.e. errors w/ a code that an api call produced
const ExpectedQueryErrorsFallback: FC<FallbackProps> = ({ error, resetErrorBoundary }) => {
const client = useQueryClient();
// adjust typing, as we may have caught an api error here w/ a code property
const caughtError = error as CaughtError;

// User needs to Login
if (caughtError.code === ErrorCodes.NOT_AUTHENTICATED) {
console.log("clearing query cache for unauthenticated user");
client.clear();
// Before we show a Login screen, check to see if we need to redirect to www site
// Redirects if it's the root, no user, and no gp cookie present (has logged in recently)
if (isGitpodIo() && window.location.pathname === "/" && window.location.hash === "") {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,18 @@ import { getGitpodService } from "../../service/service";
export const useSuggestedRepositories = () => {
const { data: org } = useCurrentOrg();

return useQuery(["suggested-repositories", { orgId: org?.id }], async () => {
if (!org) {
throw new Error("No org selected");
}
return useQuery(
["suggested-repositories", { orgId: org?.id }],
async () => {
if (!org) {
throw new Error("No org selected");
}

return await getGitpodService().server.getSuggestedRepositories(org.id);
});
return await getGitpodService().server.getSuggestedRepositories(org.id);
},
{
// Keeps data in cache for 24h - will still refresh though
cacheTime: 1000 * 60 * 60 * 24,
},
);
};
6 changes: 6 additions & 0 deletions components/dashboard/src/data/setup.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,12 @@ export function isNoPersistence(queryKey: QueryKey): boolean {

export const setupQueryClientProvider = () => {
const client = new QueryClient({
defaultOptions: {
queries: {
// Default stale time to help avoid re-fetching data too frequently
staleTime: 1000 * 5, // 5 seconds
},
},
queryCache: new QueryCache({
// log any errors our queries throw
onError: (error) => {
Expand Down
64 changes: 33 additions & 31 deletions components/dashboard/src/menu/Menu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,38 @@ const UserMenu: FC<UserMenuProps> = ({ user, className, withAdminLink, withFeedb
return items;
}, [onFeedback, user?.rolesOrPermissions, withAdminLink, withFeedbackLink]);

const menuEntries = useMemo(() => {
return [
{
title: (user && (User.getPrimaryEmail(user) || user?.name)) || "User",
customFontStyle: "text-gray-400",
separator: true,
},
{
title: "User Settings",
link: "/user/settings",
},
{
title: "Docs",
href: "https://www.gitpod.io/docs/",
target: "_blank",
rel: "noreferrer",
},
{
title: "Help",
href: "https://www.gitpod.io/support/",
target: "_blank",
rel: "noreferrer",
separator: true,
},
...extraSection,
{
title: "Log out",
href: gitpodHostUrl.asApiLogout().toString(),
},
];
}, [extraSection, user]);

return (
<div
className={classNames(
Expand All @@ -199,37 +231,7 @@ const UserMenu: FC<UserMenuProps> = ({ user, className, withAdminLink, withFeedb
)}
data-analytics='{"label":"Account"}'
>
<ContextMenu
menuEntries={[
{
title: (user && (User.getPrimaryEmail(user) || user?.name)) || "User",
customFontStyle: "text-gray-400",
separator: true,
},
{
title: "User Settings",
link: "/user/settings",
},
{
title: "Docs",
href: "https://www.gitpod.io/docs/",
target: "_blank",
rel: "noreferrer",
},
{
title: "Help",
href: "https://www.gitpod.io/support/",
target: "_blank",
rel: "noreferrer",
separator: true,
},
...extraSection,
{
title: "Log out",
href: gitpodHostUrl.asApiLogout().toString(),
},
]}
>
<ContextMenu menuEntries={menuEntries}>
<img className="rounded-full w-8 h-8" src={user?.avatarUrl || ""} alt={user?.name || "Anonymous"} />
</ContextMenu>
</div>
Expand Down
6 changes: 4 additions & 2 deletions components/dashboard/src/user-context.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,9 @@ const UserContextProvider: React.FC = ({ children }) => {
const doSetUser = useCallback(
(updatedUser: User) => {
updateErrorUserDetails(updatedUser);
if (user?.id !== updatedUser.id) {
// If user has changed clear cache
// Ignore the case where user hasn't been set yet - initial load
if (user && user?.id !== updatedUser.id) {
client.clear();
}
setUser(updatedUser);
Expand All @@ -53,7 +55,7 @@ const UserContextProvider: React.FC = ({ children }) => {
}, frequencyMs);
}
},
[user?.id, setUser, client],
[user, client],
);

// Wrap value in useMemo to avoid unnecessary re-renders
Expand Down

0 comments on commit b02c94d

Please sign in to comment.