Skip to content

Commit

Permalink
refactor: remove useAuth isLoading status
Browse files Browse the repository at this point in the history
  • Loading branch information
985563349 committed Dec 14, 2022
1 parent dc32c03 commit 503dcc9
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 13 deletions.
1 change: 0 additions & 1 deletion src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { RouterProvider } from 'react-router-dom';

import router from './router';

function App() {
Expand Down
30 changes: 18 additions & 12 deletions src/contexts/AuthProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,20 @@ import { createContext, useContext, useEffect, useReducer } from 'react';
import { flushSync } from 'react-dom';

import { request } from '@/utils/request';
import Loading from '@/components/Loading';

type AuthState = {
type AuthContextState = {
isLoading: boolean;
isAuthenticated: boolean;
user?: any;
};

export type AuthContextInterface = AuthState & {
login: (data: any, callback?: VoidFunction) => Promise<void>;
logout: (callback?: VoidFunction) => Promise<void>;
};

type Action =
| { type: 'INITIALISED'; user: any }
| { type: 'LOGOUT' }
| { type: 'LOADING'; isLoading: boolean };

const reducer = (state: AuthState, action: Action): AuthState => {
const reducer = (state: AuthContextState, action: Action): AuthContextState => {
switch (action.type) {
case 'INITIALISED':
return {
Expand Down Expand Up @@ -49,7 +45,12 @@ const reducer = (state: AuthState, action: Action): AuthState => {

const hasAuth = () => localStorage.getItem('Token') !== null;

const AuthContext = createContext<AuthContextInterface>(null!);
export type AuthContextValue = Omit<AuthContextState, 'isLoading'> & {
login: (data: any, callback?: VoidFunction) => Promise<void>;
logout: (callback?: VoidFunction) => Promise<void>;
};

const AuthContext = createContext<AuthContextValue>(null!);

export function AuthProvider({ children }: { children: React.ReactNode }) {
const [state, dispatch] = useReducer(reducer, {
Expand Down Expand Up @@ -101,11 +102,16 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
});
};

const contextValue = { ...state, login, logout };

return (
<AuthContext.Provider value={contextValue}>
{state.isLoading === false && children}
<AuthContext.Provider
value={{
isAuthenticated: state.isAuthenticated,
user: state.user,
login,
logout,
}}
>
{state.isLoading ? <Loading /> : children}
</AuthContext.Provider>
);
}
Expand Down

0 comments on commit 503dcc9

Please sign in to comment.