Persist authentication data on localStorage
This commit is contained in:
parent
31fbc1594d
commit
34c5dcd863
4 changed files with 18 additions and 5 deletions
|
@ -1,5 +1,5 @@
|
|||
import { Fragment } from 'react';
|
||||
import { Route, Routes } from 'react-router-dom';
|
||||
import { Navigate, Route, Routes } from 'react-router-dom';
|
||||
|
||||
import Login from './screens/Login';
|
||||
import UnauthenticatedHome from './screens/UnauthenticatedHome';
|
||||
|
@ -10,7 +10,7 @@ function UnauthenticatedApp() {
|
|||
<Routes>
|
||||
<Route path="/" element={<UnauthenticatedHome />} />
|
||||
<Route path="/login" element={<Login />} />
|
||||
<Route path="*" element={<h1>Route not found!</h1>} />
|
||||
<Route path="*" element={<Navigate to="/" />} />
|
||||
</Routes>
|
||||
</Fragment>
|
||||
);
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
import { createContext, useContext, useState } from 'react';
|
||||
import { createContext, useContext, useEffect, useState } from 'react';
|
||||
import { sleep } from '../utils/sleep';
|
||||
|
||||
const getUser = shouldFail =>
|
||||
|
@ -11,6 +11,7 @@ const getUser = shouldFail =>
|
|||
username: 'leonardomurca',
|
||||
name: 'Leonardo',
|
||||
lastName: 'Murça',
|
||||
token: 'skdfb9458hnsdfsif4w38r9234ry98423',
|
||||
};
|
||||
}
|
||||
});
|
||||
|
@ -24,6 +25,17 @@ function AuthProvider(props) {
|
|||
error: null,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
async function bootstrapUser() {
|
||||
const user = window.localStorage.getItem('$USER');
|
||||
if (user) {
|
||||
console.log(user);
|
||||
setState({ status: 'success', user: JSON.parse(user), error: null });
|
||||
}
|
||||
}
|
||||
bootstrapUser();
|
||||
}, [setState]);
|
||||
|
||||
const login = (email, password) => {
|
||||
setState({ ...state, status: 'pending' });
|
||||
let shouldFail = email !== 'leo@gmail.com' && password !== '#leo1234';
|
||||
|
@ -32,6 +44,7 @@ function AuthProvider(props) {
|
|||
if (shouldFail) {
|
||||
return setState({ status: 'error', user: null, error: data });
|
||||
} else {
|
||||
window.localStorage.setItem('$USER', JSON.stringify(data));
|
||||
return setState({ status: 'success', user: data, error: null });
|
||||
}
|
||||
});
|
||||
|
|
|
@ -66,6 +66,7 @@ function useUser() {
|
|||
const isPending = state.status === 'pending';
|
||||
|
||||
return {
|
||||
state,
|
||||
isPending,
|
||||
classrooms,
|
||||
};
|
||||
|
|
|
@ -1,8 +1,7 @@
|
|||
import { useUser } from '../../context/user';
|
||||
|
||||
function Home() {
|
||||
const { isPending, state, classrooms } = useUser();
|
||||
console.log(state);
|
||||
const { isPending, classrooms } = useUser();
|
||||
|
||||
return (
|
||||
<div>
|
||||
|
|
Loading…
Reference in a new issue