Skip to content

Commit

Permalink
vinvoor: move user to tanstack query
Browse files Browse the repository at this point in the history
  • Loading branch information
Topvennie committed Sep 10, 2024
1 parent 85dd558 commit 09af9cd
Show file tree
Hide file tree
Showing 23 changed files with 133 additions and 154 deletions.
10 changes: 5 additions & 5 deletions vinvoor/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
import { Box, Container } from "@mui/material";
import { useContext, useState } from "react";
import { useState } from "react";
import { Navigate, Outlet, useOutlet } from "react-router-dom";
import { LoadingSkeleton } from "./components/LoadingSkeleton";
import { NavBar } from "./navbar/NavBar";
import { Overview } from "./overview/Overview";
import { UserContext } from "./providers/UserProvider";
import { WelcomePage } from "./WelcomePage";
import { randomInt } from "./util/util";
import "./themes/background.css";
import { useUser } from "./hooks/useUser";

export const App = () => {
const { user, loading, error } = useContext(UserContext);
const { data: user, isLoading, isError } = useUser();
const outlet = useOutlet();

const [backgroundSix] = useState(() => randomInt(0, 50) === 1);
Expand All @@ -24,8 +24,8 @@ export const App = () => {
my: "2%",
}}
>
<LoadingSkeleton isLoading={loading} isError={error !== undefined}>
{user !== undefined ? (
<LoadingSkeleton isLoading={isLoading} isError={isError}>
{user && Object.keys(user).length > 0 ? (
outlet !== null ? (
<Outlet />
) : (
Expand Down
2 changes: 1 addition & 1 deletion vinvoor/src/WelcomePage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { GitHub } from "@mui/icons-material";
import { Box, Button, Typography } from "@mui/material";
import { ShakerOutline } from "mdi-material-ui";
import { TypographyG } from "./components/TypographyG";
import { Login } from "./user/Login";
import { Login } from "./auth/Login";

declare module "@mui/material/Button" {
interface ButtonPropsColorOverrides {
Expand Down
File renamed without changes.
12 changes: 12 additions & 0 deletions vinvoor/src/auth/Logout.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { Button, ButtonProps } from "@mui/material";
import { FC } from "react";
import { useLogout } from "../hooks/useUser";

export const Logout: FC<ButtonProps> = props => {
const logout = useLogout();
const handleClick = () => {
logout.mutate();
};

return <Button onClick={handleClick} {...props} />;
};
2 changes: 1 addition & 1 deletion vinvoor/src/components/LoadingSkeleton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export const LoadingSkeleton: FC<LoadingSkeletonProps> = ({
...props
}) => {
if (isError)
throw new Error("Error fetching data. Unable to reach the server");
throw new Error("Error fetching data, unable to reach the server");

return isLoading ? <Skeleton {...props} /> : <>{children}</>;
};
6 changes: 3 additions & 3 deletions vinvoor/src/components/ProtectedRoute.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { FC, ReactNode, useContext } from "react";
import { FC, ReactNode } from "react";
import { Navigate } from "react-router-dom";
import { UserContext } from "../providers/UserProvider";
import { useUser } from "../hooks/useUser";

interface ProtectedRouteProps {
children: ReactNode;
}

export const ProtectedRoute: FC<ProtectedRouteProps> = ({ children }) => {
const { user } = useContext(UserContext);
const { data: user } = useUser();

if (!user?.admin) return <Navigate to="/" replace />;

Expand Down
2 changes: 1 addition & 1 deletion vinvoor/src/hooks/useCard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { getApi, patchApi } from "../util/fetch";
const ENDPOINT = "cards";

export const useCards = () =>
useQuery<Card[]>({
useQuery({
queryKey: ["cards"],
queryFn: () => getApi<Card[], CardJSON[]>(ENDPOINT, convertCardJSON),
retry: 1,
Expand Down
35 changes: 35 additions & 0 deletions vinvoor/src/hooks/useUser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { getApi, isResponseNot200Error, postApi } from "../util/fetch";
import { convertUserJSON, User, UserJSON } from "../types/user";

const ENDPOINT = "user";

export const useUser = () =>
useQuery({
queryKey: ["user"],
queryFn: async () => {
let user = {} as User;

try {
user = await getApi<User, UserJSON>(ENDPOINT, convertUserJSON);
} catch (error) {
if (!isResponseNot200Error(error))
throw new Error("Failed to fetch user");
}

return user;
},
retry: 1,
});

export const useLogout = () => {
const queryClient = useQueryClient();

return useMutation({
mutationFn: () => postApi("logout"),
onSuccess: () =>
queryClient.invalidateQueries({
queryKey: ["user"],
}),
});
};
7 changes: 3 additions & 4 deletions vinvoor/src/leaderboard/LeaderboardTableBody.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,13 @@ import {
Typography,
} from "@mui/material";
import { alpha, Theme, useTheme } from "@mui/material/styles";
import { useContext } from "react";
import { UserContext } from "../providers/UserProvider";
import { TableHeadCell } from "../types/general";
import { leaderboardHeadCells, LeaderboardItem } from "../types/leaderboard";
import FirstPlaceIcon from "/first_place.svg";
import SecondPlaceIcon from "/second_place.svg";
import ThirdPlaceIcon from "/third_place.svg";
import { useLeaderboardItems } from "../hooks/useLeaderboard";
import { useUser } from "../hooks/useUser";

const leaderboardColors = [
(theme: Theme) => theme.leaderboard.first,
Expand Down Expand Up @@ -105,7 +104,7 @@ export const LeaderboardTableBody = () => {
if (!rows) return null; // Can never happen

const theme = useTheme();
const { user } = useContext(UserContext);
const { data: user } = useUser();

return (
<TableBody>
Expand All @@ -118,7 +117,7 @@ export const LeaderboardTableBody = () => {
...(index % 2 === 0 && {
backgroundColor: theme => theme.palette.action.hover,
}),
...(row.name === user!.username && {
...(row.name === user!.name && {
backgroundColor: theme =>
alpha(
theme.palette.primary.main,
Expand Down
7 changes: 3 additions & 4 deletions vinvoor/src/leaderboard/LeaderboardTableToolbar.tsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,17 @@
import { MoveDown } from "@mui/icons-material";
import { Button, Toolbar, Typography } from "@mui/material";
import { useContext } from "react";
import { HashLink } from "react-router-hash-link";
import { UserContext } from "../providers/UserProvider";
import { useUser } from "../hooks/useUser";

export const LeaderboardTableToolbar = () => {
const { user } = useContext(UserContext);
const { data: user } = useUser();

return (
<Toolbar sx={{ p: { xs: 1, sm: 2 }, m: { xs: 1, sm: 2 } }}>
<Typography sx={{ flex: "1" }} variant="h4" fontWeight="bold">
Ranking
</Typography>
<HashLink to={`/leaderboard#${user!.username}`}>
<HashLink to={`/leaderboard#${user!.name}`}>
<Button variant="contained">
<MoveDown sx={{ mr: "2%" }} />
<Typography>Jump</Typography>
Expand Down
20 changes: 9 additions & 11 deletions vinvoor/src/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ import { UserProvider } from "./providers/UserProvider.tsx";
import { Scans } from "./scans/Scans.tsx";
import { Admin } from "./settings/admin/Admin.tsx";
import { SettingsOverview } from "./settings/SettingsOverview.tsx";
import { Login } from "./user/Login.tsx";
import { Logout } from "./user/Logout.tsx";
import { Login } from "./auth/Login.tsx";
import { Logout } from "./auth/Logout.tsx";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { NavBar } from "./navbar/NavBar.tsx";

Expand Down Expand Up @@ -77,15 +77,13 @@ ReactDOM.createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<ThemeProvider>
<CssBaseline enableColorScheme>
<UserProvider>
<QueryClientProvider client={queryClient}>
<ConfirmProvider>
<CustomSnackbarProvider>
<RouterProvider router={router} />
</CustomSnackbarProvider>
</ConfirmProvider>
</QueryClientProvider>
</UserProvider>
<QueryClientProvider client={queryClient}>
<ConfirmProvider>
<CustomSnackbarProvider>
<RouterProvider router={router} />
</CustomSnackbarProvider>
</ConfirmProvider>
</QueryClientProvider>
</CssBaseline>
</ThemeProvider>
</React.StrictMode>,
Expand Down
6 changes: 3 additions & 3 deletions vinvoor/src/navbar/NavBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@ import {
CreditCardMultipleOutline,
CreditCardScanOutline,
} from "mdi-material-ui";
import { useContext, useState } from "react";
import { useState } from "react";
import { DarkModeToggle } from "../components/DarkModeToggle";
import { UserContext } from "../providers/UserProvider";
import { NavBarLogo } from "./NavBarLogo";
import { NavBarPages } from "./NavBarPages";
import { NavBarSandwich } from "./NavBarSandwich";
import { NavBarUserMenu } from "./NavBarUserMenu";
import { useUser } from "../hooks/useUser";

export interface PageIcon {
page: string;
Expand All @@ -29,7 +29,7 @@ const userMenuPages: PageIcon[] = [
];

export const NavBar = () => {
const { user } = useContext(UserContext);
const { data: user } = useUser();
const [selectedPage, setSelectedPage] = useState<string>("");

const screenSize = {
Expand Down
12 changes: 6 additions & 6 deletions vinvoor/src/navbar/NavBarUserMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,12 @@ import {
} from "@mui/material";
import { useTheme } from "@mui/material/styles";
import { Cow, ExitRun, ShieldAccountOutline } from "mdi-material-ui";
import { FC, MouseEvent, useContext, useState } from "react";
import { FC, MouseEvent, useState } from "react";
import { UnstyledLink } from "../components/UnstyledLink";
import { UserContext } from "../providers/UserProvider";
import { Login } from "../user/Login";
import { Logout } from "../user/Logout";
import { Login } from "../auth/Login";
import { Logout } from "../auth/Logout";
import { PageIcon } from "./NavBar";
import { useUser } from "../hooks/useUser";

interface NavBarUserMenuProps {
pageIcons: readonly PageIcon[];
Expand All @@ -26,7 +26,7 @@ export const NavBarUserMenu: FC<NavBarUserMenuProps> = ({
selectedPage,
handleSelectedPage,
}) => {
const { user } = useContext(UserContext);
const { data: user } = useUser();
const theme = useTheme();
const isBrowserView = useMediaQuery(theme.breakpoints.up("sm"));
const [anchorElUser, setAnchorElUser] = useState<HTMLElement | undefined>(
Expand Down Expand Up @@ -59,7 +59,7 @@ export const NavBarUserMenu: FC<NavBarUserMenuProps> = ({
}}
>
<ShieldAccountOutline sx={{ mr: "3px" }} />
<Typography variant="h6">{user.username}</Typography>
<Typography variant="h6">{user.name}</Typography>
</Button>
<Menu
sx={{ mt: "45px" }}
Expand Down
67 changes: 0 additions & 67 deletions vinvoor/src/providers/UserProvider.tsx

This file was deleted.

15 changes: 0 additions & 15 deletions vinvoor/src/providers/dataproviders/leaderboardProvider.ts

This file was deleted.

2 changes: 2 additions & 0 deletions vinvoor/src/types/cards.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export interface CardJSON extends BaseJSON {
name: string;
last_used: string;
amount_used: number;
created_at: string;
}

export interface CardPostResponseJSON {
Expand All @@ -28,6 +29,7 @@ export interface Card extends Base {
name: string;
lastUsed: Date;
amountUsed: number;
createdAt: Date;
}

export interface CardPostResponse {
Expand Down
1 change: 0 additions & 1 deletion vinvoor/src/types/days.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ export const convertDayJSON = (daysJSON: DayJSON[]): Day[] =>
.map(dayJSON => ({
...dayJSON,
date: new Date(dayJSON.date),
createdAt: new Date(dayJSON.created_at),
}))
.sort((a, b) => a.date.getTime() - b.date.getTime());

Expand Down
2 changes: 0 additions & 2 deletions vinvoor/src/types/general.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,10 @@ export type Optional<T> = T | undefined;

export interface BaseJSON {
id: number;
created_at: string;
}

export interface Base {
id: number;
createdAt: Date;
}

export type TableOrder = "asc" | "desc";
Expand Down
Loading

0 comments on commit 09af9cd

Please sign in to comment.