feat(ui): added new auth guard with react-query and axios

This commit is contained in:
akhilmhdh
2023-01-26 00:14:01 +05:30
parent a6f480d3f8
commit a6387e7552
16 changed files with 234 additions and 30 deletions
+1
View File
@@ -0,0 +1 @@
export { useGetAuthToken } from './queries';
+26
View File
@@ -0,0 +1,26 @@
import { useQuery } from '@tanstack/react-query';
import { apiRequest } from '@app/config/request';
import { setAuthToken } from '@app/reactQuery';
import { GetAuthTokenAPI } from './types';
const authKeys = {
getAuthToken: ['token'] as const
};
// Refresh token is set as cookie when logged in
// Using that we fetch the auth bearer token needed for auth calls
const fetchAuthToken = async () => {
const { data } = await apiRequest.post<GetAuthTokenAPI>('/api/v1/auth/token', undefined, {
withCredentials: true
});
return data;
};
export const useGetAuthToken = () =>
useQuery(authKeys.getAuthToken, fetchAuthToken, {
onSuccess: (data) => setAuthToken(data.token),
retry: 0
});
+3
View File
@@ -0,0 +1,3 @@
export type GetAuthTokenAPI = {
token: string;
};
+1
View File
@@ -0,0 +1 @@
export { useGetAuthToken } from './auth';
+1
View File
@@ -1 +1,2 @@
export { usePopUp } from './usePopUp';
export { useToggle } from './useToggle';
+30
View File
@@ -0,0 +1,30 @@
import { useCallback, useState } from 'react';
type VoidFn = () => void;
type UseToggleReturn = [
boolean,
{
on: VoidFn;
off: VoidFn;
toggle: VoidFn;
}
];
export const useToggle = (initialState = false): UseToggleReturn => {
const [value, setValue] = useState(initialState);
const on = useCallback(() => {
setValue(true);
}, []);
const off = useCallback(() => {
setValue(false);
}, []);
const toggle = useCallback((isOpen?: boolean) => {
setValue((prev) => (typeof isOpen === 'boolean' ? isOpen : !prev));
}, []);
return [value, { on, off, toggle }];
};