Skip to content

Commit

Permalink
update react-query-auth
Browse files Browse the repository at this point in the history
  • Loading branch information
alan2207 committed Dec 8, 2024
1 parent 9a45c8b commit ee7f6d5
Show file tree
Hide file tree
Showing 5 changed files with 34 additions and 73 deletions.
2 changes: 1 addition & 1 deletion apps/react-vite/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@
"react-error-boundary": "^4.0.13",
"react-helmet-async": "^2.0.4",
"react-hook-form": "^7.51.3",
"react-query-auth": "^2.3.0",
"react-query-auth": "^2.4.3",
"react-router": "^7.0.2",
"tailwind-merge": "^2.3.0",
"tailwindcss-animate": "^1.0.7",
Expand Down
10 changes: 9 additions & 1 deletion apps/react-vite/src/app/provider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,15 @@ export const AppProvider = ({ children }: AppProviderProps) => {
<QueryClientProvider client={queryClient}>
{import.meta.env.DEV && <ReactQueryDevtools />}
<Notifications />
<AuthLoader>{children}</AuthLoader>
<AuthLoader
renderLoading={() => (
<div className="flex h-screen w-screen items-center justify-center">
<Spinner size="xl" />
</div>
)}
>
{children}
</AuthLoader>
</QueryClientProvider>
</HelmetProvider>
</ErrorBoundary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ export function DashboardLayout({ children }: { children: React.ReactNode }) {
<DropdownMenuSeparator />
<DropdownMenuItem
className={cn('block px-4 py-2 text-sm text-gray-700 w-full')}
onClick={() => logout.mutate()}
onClick={() => logout.mutate({})}
>
Sign Out
</DropdownMenuItem>
Expand Down
85 changes: 19 additions & 66 deletions apps/react-vite/src/lib/auth.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,7 @@
import {
queryOptions,
useMutation,
useQuery,
useQueryClient,
} from '@tanstack/react-query';
import { configureAuth } from 'react-query-auth';
import { Navigate, useLocation } from 'react-router';
import { z } from 'zod';

import { Spinner } from '@/components/ui/spinner';
import { paths } from '@/config/paths';
import { AuthResponse, User } from '@/types/api';

Expand All @@ -16,56 +10,12 @@ import { api } from './api-client';
// api call definitions for auth (types, schemas, requests):
// these are not part of features as this is a module shared across features

export const getUser = async (): Promise<User> => {
const response = (await api.get('/auth/me')) as { data: User };
const getUser = async (): Promise<User> => {
const response = await api.get('/auth/me');

return response.data;
};

const userQueryKey = ['user'];

export const getUserQueryOptions = () => {
return queryOptions({
queryKey: userQueryKey,
queryFn: getUser,
});
};

export const useUser = () => useQuery(getUserQueryOptions());

export const useLogin = ({ onSuccess }: { onSuccess?: () => void } = {}) => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: loginWithEmailAndPassword,
onSuccess: (data) => {
queryClient.setQueryData(userQueryKey, data.user);
onSuccess?.();
},
});
};

export const useRegister = ({ onSuccess }: { onSuccess?: () => void } = {}) => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: registerWithEmailAndPassword,
onSuccess: (data) => {
queryClient.setQueryData(userQueryKey, data.user);
onSuccess?.();
},
});
};

export const useLogout = ({ onSuccess }: { onSuccess?: () => void } = {}) => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: logout,
onSuccess: () => {
queryClient.removeQueries({ queryKey: userQueryKey });
onSuccess?.();
},
});
};

const logout = (): Promise<void> => {
return api.post('/auth/logout');
};
Expand Down Expand Up @@ -109,6 +59,22 @@ const registerWithEmailAndPassword = (
return api.post('/auth/register', data);
};

const authConfig = {
userFn: getUser,
loginFn: async (data: LoginInput) => {
const response = await loginWithEmailAndPassword(data);
return response.user;
},
registerFn: async (data: RegisterInput) => {
const response = await registerWithEmailAndPassword(data);
return response.user;
},
logoutFn: logout,
};

export const { useUser, useLogin, useLogout, useRegister, AuthLoader } =
configureAuth(authConfig);

export const ProtectedRoute = ({ children }: { children: React.ReactNode }) => {
const user = useUser();
const location = useLocation();
Expand All @@ -121,16 +87,3 @@ export const ProtectedRoute = ({ children }: { children: React.ReactNode }) => {

return children;
};

export const AuthLoader = ({ children }: { children: React.ReactNode }) => {
const user = useUser();
if (!user.isFetched) {
return (
<div className="flex h-screen w-screen items-center justify-center">
<Spinner size="xl" />
</div>
);
}

return children;
};
8 changes: 4 additions & 4 deletions apps/react-vite/yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -8738,10 +8738,10 @@ react-is@^18.0.0:
resolved "https://registry.yarnpkg.com/react-is/-/react-is-18.3.1.tgz#e83557dc12eae63a99e003a46388b1dcbb44db7e"
integrity sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==

react-query-auth@^2.3.0:
version "2.3.0"
resolved "https://registry.yarnpkg.com/react-query-auth/-/react-query-auth-2.3.0.tgz#2c03e4cd3c75a01bde0cfa97168b857906315449"
integrity sha512-42IvqDxnQMOCdPmf+H8hMscO+1EgDPMuNnJrYEJwe8Itsd2z96obtlm85PvBk8BgvOQrKGEGx1VDsAIzk6y7yw==
react-query-auth@^2.4.3:
version "2.4.3"
resolved "https://registry.yarnpkg.com/react-query-auth/-/react-query-auth-2.4.3.tgz#63d0faf866a5844b18c89257f9c17121ac3b682c"
integrity sha512-sSDX4OZSyBTvTOItiWEH/SsTfKg7AEAc7qOL1qsxx+vIx5s82VeUyj4W1vNlHY9nFeU1accm1hRW1FVF2TzaiA==

react-refresh@^0.14.0:
version "0.14.2"
Expand Down

0 comments on commit ee7f6d5

Please sign in to comment.