Skip to content

Instantly share code, notes, and snippets.

@guimochila
Created September 21, 2021 14:54
Show Gist options
  • Save guimochila/80a30607389b508cf9ccd80b03b42fdd to your computer and use it in GitHub Desktop.
Save guimochila/80a30607389b508cf9ccd80b03b42fdd to your computer and use it in GitHub Desktop.
Authentication in React App - Typescript
import * as React from 'react';
import { client } from '../utils/httpClient';
type User = {
_id: string;
name: string;
email: string;
photo: string;
credits: number;
} | null;
type State = {
user: User;
logout(): void;
loading: boolean;
};
const AuthContext = React.createContext<State | undefined>(undefined);
AuthContext.displayName = 'AuthContext';
export const AuthProvider: React.FC = (props) => {
const [user, setUser] = React.useState<User>(null);
const [loading, setLoading] = React.useState(false);
React.useEffect(() => {
async function fetchUser() {
setLoading(true);
try {
const user = await client('api/current_user');
setUser(user);
setLoading(false);
} catch (error) {
console.error(error);
setUser(null);
setLoading(false);
}
}
fetchUser();
}, []);
const logout = React.useCallback(() => {
client('api/logout').then(() => setUser(null));
}, []);
const value = React.useMemo(
() => ({ user, loading, logout }),
[user, loading, logout],
);
return <AuthContext.Provider value={value} {...props} />;
};
export const useAuth = () => {
const context = React.useContext(AuthContext);
if (context === undefined) {
throw new Error('useAuth must be used within a AuthProvider');
}
return context;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment