Skip to content

Commit

Permalink
Merge pull request #11 from UnBArqDsw2021-1/i09_auth_flow
Browse files Browse the repository at this point in the history
Criação do Fluxo de Autenticação #9
  • Loading branch information
RuanMoura authored Oct 14, 2021
2 parents 7d732e1 + 8a20269 commit 643d59d
Show file tree
Hide file tree
Showing 3 changed files with 90 additions and 11 deletions.
17 changes: 6 additions & 11 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,27 +1,22 @@
import React from "react";
// import { BrowserRouter as Router, Switch, Route } from "react-router-dom";

// Pages Imports
// import { Home } from "./pages/Home";

// Components Imports
import { Header } from "./components/Header";
import { Footer } from "./components/Footer";

import { Router } from "./routes";
import { AuthProvider } from "./hooks/useAuth";

// Styles Imports
import "./styles/global.css";

function App() {
return (
<div className="App">
<AuthProvider>
<Header />
{/* <Router>
<Switch>
<Route exact path="/" component={Home} />
</Switch>
</Router> */}
<Router />
<Footer />
</div>
</AuthProvider>
);
}

Expand Down
64 changes: 64 additions & 0 deletions src/hooks/useAuth.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import React, { createContext, useState, useEffect, useContext } from "react";

type User = {
name: string;
email: string;
};

interface AuthContextProps {
signedIn: boolean;
user: User | null;
signIn: (email: string, name: string) => void;
signOut: () => void;
}

const AuthContext = createContext({
signedIn: false,
} as AuthContextProps);

export const AuthProvider: React.FC = ({ children }) => {
const [user, setUser] = useState<User | null>(null);

useEffect(() => {
async function getStoredData() {
const _user = localStorage.getItem("@PetStop:user");

if (_user) setUser(JSON.parse(_user));
}

getStoredData();
}, []);

async function signIn(email: string, password: string): Promise<void> {
setUser({
name: "Nome de Teste",
email: "[email protected]",
});

localStorage.setItem("@PetStop:user", JSON.stringify(user));
}

async function signOut() {
setUser(null);
localStorage.removeItem("@PetStop:user");
}

return (
<AuthContext.Provider
value={{
signedIn: !!user,
user,
signIn,
signOut,
}}
>
{children}
</AuthContext.Provider>
);
};

export function useAuth() {
const context = useContext(AuthContext);

return context;
}
20 changes: 20 additions & 0 deletions src/routes.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import React from "react";
import { BrowserRouter, Switch, Route } from "react-router-dom";

// Pages Imports
import { Home } from "./pages/Home";

// Utils Imports
// import { useAuth } from "./hooks/useAuth";

export function Router() {
// const { signedIn } = useAuth();

return (
<BrowserRouter>
<Switch>
<Route path="/" exact component={Home} />
</Switch>
</BrowserRouter>
);
}

0 comments on commit 643d59d

Please sign in to comment.