I am making a site whereby after the user signs in, the user is meant to be redirected to the home page. The homepage and all the other pages of the site are only accessible by signed in users but even after a user signs in(firebase auth), the rest of the site(protected routes) is still not accessible and the only page accessible is the login page. The technologies I am using are react, react router dom and firebase and this is how my code looks like, starting with the App.js
import Home from "./pages/home/Home";
import Login from "./pages/login/Login";
import { BrowserRouter, Navigate, Route, Routes } from "react-router-dom";
import List from "./pages/list/List";
import User from "./pages/user/User";
import AddNew from "./pages/addnew/AddNew";
import { useContext } from "react";
import { AuthContext } from "./context/AuthContext";
function App() {
const {currentUser} = useContext(AuthContext);
const RequireAuth = ({ children }) => {
return currentUser ? children : <Navigate to="/login" />;
};
return (
<div className="App">
<BrowserRouter>
<Routes>
<Route path="/login" exact element={<Login />} />
<Route path="/" exact element={ <RequireAuth> <Home /> </RequireAuth> } />
<Route path="/users" exact element={<RequireAuth><List /></RequireAuth>} />
<Route path="/users/:id" exact element={<RequireAuth><User /></RequireAuth>} />
<Route path="/add" exact element={<RequireAuth><AddNew /></RequireAuth>} />
</Routes>
</BrowserRouter>
</div>
);
}
export default App;
And then followed by the login.js page
import React,{useState} from 'react'
import { useContext } from 'react';
import { signInWithEmailAndPassword } from "firebase/auth";
import { auth } from '../../firebase';
import "./login.css";
import {useNavigate} from "react-router-dom";
import { AuthContext } from '../../context/AuthContext';
export default function Login() {
const [error, seterror] = useState(false);
const [email, setemail] = useState("");
const [password, setpassword] = useState("");
const navigate = useNavigate();
const {dispatch} = useContext(AuthContext)
const handleLogin = (e) => {
e.preventDefault();
signInWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
const user = userCredential.user;
dispatch({type: "LOGIN", payload: user});
navigate("/");
})
.catch((error) => {
seterror(true);
console.log(error.message);
});
}
return (
<div className='login'>
<form onSubmit={handleLogin}>
<input className='ok' type="email" placeholder='email' onChange={e => setemail(e.target.value)} />
<input className='ok' type="password" placeholder='password' onChange={e => setpassword(e.target.value)} />
<button className='sb'>Submit</button>
{error && <span className='ks'>Wrong email or password</span>}
</form>
</div>
)
}
And then I have the authreducer.js file that deals with the state
const AuthReducer = (state, action) => {
switch (action.type) {
case "LOGIN": {
return {
currentUser: action.payload,
}
}
case "LOGOUT": {
return {
currentUser: null
}
}
default:
return state;
}
}
export default AuthReducer
And finally the authcontext.js file
import { createContext, useEffect, useReducer } from "react";
import AuthReducer from "./AuthReducer";
const INITIAL_STATE = {
currentUser: JSON.parse(localStorage.getItem("user")) || null,
}
export const AuthContext = createContext(INITIAL_STATE);
export const AuthContextProvider = ({children}) => {
const [state, dispatch] = useReducer(AuthReducer, INITIAL_STATE);
useEffect(() => {
localStorage.setItem("user", JSON.stringify(state.currentUser))
}, [state.currentUser])
return (
<AuthContext.Provider value={{current: state.current, dispatch}}>
{children}
</AuthContext.Provider>
)
}
I do not know what could be causing this problem but I have an idea that it has something to do with the state because it was redirecting well before I started combining it with the state. What could be the problem
Issue
From that I can see, the App isn't destructuring the correct context value to handle the conditional route protection.
The AuthContextProvider provides a context value with current and dispatch properties
<AuthContext.Provider value={{ current: state.current, dispatch }}>
{children}
</AuthContext.Provider>
but App is accessing a currentUser property, which is going to be undefined because state.current is undefined.
const { currentUser } = useContext(AuthContext);
const RequireAuth = ({ children }) => {
return currentUser ? children : <Navigate to="/login" />;
};
The Navigate component will always be rendered.
Solution
Assuming the handleLogin handler correctly updates the state then the solution is to be consistent with state properties.
<AuthContext.Provider value={{ currentUser: state.currentUser, dispatch }}>
{children}
</AuthContext.Provider>
...
const { currentUser } = useContext(AuthContext);
const RequireAuth = ({ children }) => {
return currentUser ? children : <Navigate to="/login" />;
};
Related
I'm trying to use the Context Api to save the user data that comes from the firebase api, but when I get these values in the component Index, it always returns the error:
TypeError: Object is not iterable (cannot read property Symbol(Symbol.iterator))
Below is my code
Where do I create the Context
import React, { createContext, useState } from "react";
const Context = createContext();
function AuthProvider({children}) {
const [userLogin, setUserLogin] = useState({});
return (
<Context.Provider value={{ userLogin, setUserLogin }} >
{ children }
</Context.Provider>
);
}
export { Context, AuthProvider }
Route File
<React.StrictMode>
<BrowserRouter>
<AuthProvider>
<Routes>
<Route path='/' element={<Login />} />
<Route path='/cadastrar' element={<Register />} />
<Route path='/recuperar-senha' element={<Recovery />} />
<Route path='/anuncios' exact element={<Index />} />
</Routes>
</AuthProvider>
</BrowserRouter>
</React.StrictMode>
Here where I set the context with firebase data
const {setUserLogin} = useContext(Context);
const { register, handleSubmit, formState: { errors } } = useForm();
const onSubmit = data => {
const auth = getAuth();
signInWithEmailAndPassword(auth, data.email, data.password)
.then((userCredential) => {
const user = userCredential.user;
setUserLogin({user});
navigate('/anuncios');
})
.catch((error) => {
let erroMessage = localizeErrorMap(error.code)
Toast('error', erroMessage);
})
};
I want to save the data in the context api and be able to take, for example, the component below and the others
import React, {useContext} from "react";
import { Context } from '../providers/auth';
export default function Index() {
const [user, setUserLogin] = useContext(Context);
//console.log(user);
return (
<h1>Logado {user}</h1>
)
}
I saw that in the browser console when I click on the component, it informs that the problem is in the line: const [user, setUserLogin] = useContext(Context);
Your context value is { userLogin, setUserLogin }:
<Context.Provider value={{ userLogin, setUserLogin }}>
so you cannot destructure it into an array. Use const { userLogin, setUserLogin } = useContext(Context) instead:
export default function Index() {
const { userLogin, setUserLogin } = useContext(Context);
console.log(userLogin);
...
I have been using React for close to a year know and understand a majority of the basics, however I have some questions regarding best practices (General or industry) when it comes to passing functions/ref/hooks and how it affects things like state flow and tests. I have been instantiating hooks such as useDispatch or useNavigation(React-router) in the App.tsx(js) file and then passing it down to all of my components who need to use it. I have been using this same concept for things like Axios and then within my components, I've been trying out passing MUI components(Grid, Card, etc) to my created component (i.e. LoginForm.tsx/js) where the initial rendering of the main component brings in those hooks instead of repeated instantiation throughout my project (Below for example). Is this breaking in standards or practices, such as SOLID OOP, and would this make testing harder down the line?
App.tsx
import { Dispatch, FC, Suspense, lazy } from "react";
import {
Navigate,
NavigateFunction,
Route,
Routes,
useNavigate,
useSearchParams,
} from "react-router-dom";
import {
HOMEPAGE,
LOGIN,
REDIRECT,
ROOM,
SEARCH,
SETUPROOM,
SIGNUP,
} from "./component/UI/Constatns";
import Layout from "./component/UI/Layout/Layout";
import { User } from "./types/types";
import { useDispatch, useSelector } from "react-redux";
import { RootState } from "./store/store";
import { Theme, useMediaQuery, useTheme } from "#mui/material";
import axios from "axios";
import LoadingSpinner from "./component/UI/LoadingSpinner";
const Homepage = lazy(() => import("./pages/Homepage"));
const Login = lazy(() => import("./pages/Login"));
const Signup = lazy(() => import("./pages/Signup"));
const Room = lazy(() => import("./pages/Room"));
const Search = lazy(() => import("./pages/subpages/Search"));
const CreateRoom = lazy(() => import("./pages/subpages/CreateRoom"));
const App: FC = () => {
const USER: User = useSelector((state: RootState) => state.user);
const theme: Theme = useTheme();
const isMobile: boolean = useMediaQuery(theme.breakpoints.down("md"));
const [params] = useSearchParams();
const dispatch: Dispatch<any> = useDispatch();
const navigation: NavigateFunction = useNavigate();
return (
<Suspense fallback={<LoadingSpinner />}>
<Layout>
<Routes>
<Route
path={HOMEPAGE}
element={
<Homepage
user={USER}
isMobile={isMobile}
axios={axios}
dispatch={dispatch}
param={params}
/>
}
/>
<Route
path={SEARCH}
element={
<Search
axios={axios}
dispatch={dispatch}
params={params}
nav={navigation}
isMobile={isMobile}
/>
}
/>
<Route
path={ROOM}
element={
<Room
isMobile={isMobile}
nav={navigation}
dispatch={dispatch}
param={params}
/>
}
/>
<Route
path={SETUPROOM}
element={
<CreateRoom
params={params}
axios={axios}
nav={navigation}
isMobile={isMobile}
user={USER}
/>
}
/>
<Route
path={LOGIN}
element={
<Login
nav={navigation}
isMobile={isMobile}
params={params}
axios={axios}
dispatch={dispatch}
/>
}
/>
<Route
path={SIGNUP}
element={
<Signup nav={navigation} isMobile={isMobile} axios={axios} />
}
/>
<Route path={REDIRECT} element={<Navigate replace to={HOMEPAGE} />} />
</Routes>
</Layout>
</Suspense>
);
};
export default App;
Example of MUI hooks
import { Button, Card, CardContent, Grid, TextField } from "#mui/material";
import { AxiosStatic } from "axios";
import { Dispatch, FC, FormEvent, useEffect, useRef, useState } from "react";
import { NavigateFunction, NavLink } from "react-router-dom";
import { FETCHLOGIN, HOMEPAGE, LOGGEDIN } from "../component/UI/Constatns";
import { userActions } from "../store/user/user-slice";
import LoginForm from "../component/forms/login/LoginForm";
import classes from "../styles/LoginStyles.module.css";
const Login: FC<{
dispatch: Dispatch<any>;
isMobile: boolean;
params: URLSearchParams;
axios: AxiosStatic;
nav: NavigateFunction;
}> = ({ axios, dispatch, isMobile, params, nav }) => {
const [userPassword, setUserPassword] = useState<string>("");
const username = useRef<HTMLInputElement | undefined>();
const password = useRef<HTMLInputElement | undefined>();
const userSearchParam: string | null = params.get("username");
useEffect(() => {
if (userSearchParam) {
const fetchUser: (
axios: AxiosStatic,
username: string,
password: string
) => void = async (axios, username, password) => {
await axios
.post(FETCHLOGIN, { username: username, password: password })
.then((response) => {
dispatch(userActions.login({ username: response.data.username }));
nav(LOGGEDIN, { replace: true });
})
.catch(() => {
nav(HOMEPAGE, { replace: true });
});
};
fetchUser(axios, userSearchParam, userPassword);
}
}, [nav, axios, userPassword, userSearchParam, dispatch]);
const submitHandler: (e: FormEvent<HTMLFormElement>) => void = (e) => {
e.preventDefault();
setUserPassword(password.current?.value as string);
nav(`?username=${username.current?.value}`, { replace: true });
};
return (
<Grid className={classes.loginContainer} container>
<Card className={!isMobile ? classes.card : classes.mobCard}>
<div className={classes.cardHeader}>
<p>Please login</p>
</div>
<CardContent>
<LoginForm
Link={NavLink}
Submit={submitHandler}
TextField={TextField}
Button={Button}
Grid={Grid}
username={username}
password={password}
/>
</CardContent>
</Card>
</Grid>
);
};
export default Login;
I am making a simple SPA where you need to login before you can access other pages. I can successfully login and store the login data (firstname, lastname, etc.) cause I plan to use the data again later in the other pages. The problem is whenever I refresh the page, it always empty the state in the context which cause me to return to the login page. I am referring link for my SPA.
Do I need to do this? I would be thankful if someone can point out what I should change / improve. Thank you.
Here is my code.
App.js
import React, { useState } from "react";
import { BrowserRouter as Router, Link, Route } from "react-router-dom";
import { AuthContext } from "./context/auth";
import PrivateRoute from "./PrivateRoute";
import Login from "./pages/Login";
import Signup from "./pages/Signup";
import Home from "./pages/Home";
import Admin from "./pages/Admin";
function App() {
const [authTokens, setAuthTokens] = useState();
const setTokens = (data) => {
// console.log("DATA ",data);
localStorage.setItem("tokens", JSON.stringify(data));
setAuthTokens(data);
}
// console.log(authTokens);
return (
<AuthContext.Provider value={{ authTokens, setAuthTokens: setTokens }}>
<Router>
<div className="app">
<ul>
<li><Link to="/">Home Page</Link></li>
<li><Link to="/admin">Admin Page</Link></li>
</ul>
<Route exact path="/login" component={Login} />
<Route exact path="/signup" component={Signup} />
<Route exact path="/" component={Home} />
<PrivateRoute exact path="/admin" component={Admin} />
</div>
</Router>
</AuthContext.Provider>
);
}
export default App;
Login.js
import React, { useState } from "react";
import axios from "axios";
import { Link, Redirect } from "react-router-dom";
import { useAuth } from "../context/auth";
import { Card, Form, Input, Button, Error } from "../components/AuthForm";
const Login = () => {
const [isLoggedIn, setLoggedIn] = useState(false);
const [isError, setIsError] = useState(false);
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const { setAuthTokens } = useAuth();
const handleLogin = () => {
axios
.post("LOGINLINK", {
email,
password,
})
.then((result) => {
if (result.status === 200) {
setAuthTokens(result.data);
setLoggedIn(true);
} else {
setIsError(true);
}
})
.catch((error) => {
setIsError(true);
});
};
if (isLoggedIn) {
return <Redirect to="/" />;
}
return (
<Card>
<Form>
<Input
type="email"
placeholder="Email"
value={email}
onChange={(e) => {
setEmail(e.target.value);
}}
/>
<Input
type="password"
placeholder="password"
value={password}
onChange={(e) => {
setPassword(e.target.value);
}}
/>
<Button onClick={handleLogin}>Login</Button>
</Form>
<Link to="/signup">Don't have an account?</Link>
{isError && (
<Error>The username or password provided were incorrect!</Error>
)}
</Card>
);
};
export default Login;
Auth.js
import { createContext, useContext } from "react";
export const AuthContext = createContext();
export function useAuth() {
console.log("CONTEXT", useContext(AuthContext));
return useContext(AuthContext);
}
In your App component you need to fetch the data from localStorage when initializing your state so it has some data to start with.
const localToken = JSON.parse(localStorage.getItem("tokens"));
const [authTokens, setAuthTokens] = useState(localToken);
If user has already authenticated it will be available in localStorage else it's going to be null.
I also had same problem but I solved liked this Don't use localStorage directly use your state and if it is undefined then only use localStorage. cause directly manipulating state with localStorage is in contrast with react internal state and effects re-render .
const getToken = () => {
JSON.parse(localStorage.getItem('yourtoken') || '')
}
const setToken = (token) => {
localStorage.setItem('key' , token)
}
const [authTokens, setAuthTokens] = useState(getToken());
const setTokens = (data) => {
// console.log("DATA ",data);
setToken(token);
setAuthTokens(data);
}
I'm creating a ProtectedRoute component in React that will take a user state variable as prop.
This user is from my checkUser() func using amplify's Auth.currentAuthenticatedUser().
function App() {
const [user, setUser] = useState();
const { Auth, Hub } = useContext(AmplifyContext)
async function checkUser() {
try {
const loggedInUser = await Auth.currentAuthenticatedUser();
setUser(loggedInUser);
console.log(loggedInUser);
// get null first time?
} catch(e) {
setUser(null);
console.log(e.message);
}
}
useEffect(() => {
checkUser();
}, [Auth])
return (
<Router>
<Suspense fallback={<p>...loading...</p>}>
<Switch>
<IsUserLoggedIn user={user} loggedInPath={ROUTES.DASHBOARD} path={ROUTES.LOGIN}>
<Route path={ROUTES.LOGIN} component={Login} />
</IsUserLoggedIn>
<IsUserLoggedIn user={user} loggedInPath={ROUTES.DASHBOARD} path={ROUTES.SIGN_UP}>
<Route path={ROUTES.SIGN_UP} component={SignUp} />
</IsUserLoggedIn>
<ProtectedRoute user={user} path={ROUTES.DASHBOARD} exact>
<Route path={ROUTES.DASHBOARD} exact component={Dashboard} />
</ProtectedRoute>
<Route path={ROUTES.RESET_PW} component={ResetPw} />
<Route component={NoPage} />
</Switch>
</Suspense>
</Router>
);
}
// Protected Route Component
import { Route, Redirect } from "react-router-dom";
import * as ROUTES from '../constants/routes';
export default function ProtectedRoute({user, children, ...restProps}) {
console.log(user);
return (
<Route
{...restProps}
render={({location}) => {
if(user) {
return children;
}
if(!user) {
return (
<Redirect
to={{
pathname: ROUTES.LOGIN,
state: { from: location }
}}
/>
)
}
return null;
}}
/>
)
}
// login component
import { useState, useContext } from "react";
import { Link } from "react-router-dom";
import { useHistory } from 'react-router';
import AmplifyContext from "../context/amplify";
import * as ROUTES from '../constants/routes';
export default function Login() {
const { Auth, Hub } = useContext(AmplifyContext);
const history = useHistory();
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const invalid = !username || !password;
const handleLogin = async (e) => {
e.preventDefault();
try {
// amplify Auth login
await Auth.signIn(username, password);
history.push(ROUTES.DASHBOARD);
console.log('logged in');
} catch(e) {
setError(e.message);
setPassword('');
}
}
return (
<div className="auth-container">
<h2 className="auth-title">Log In</h2>
<div className="login-form-container">
<form className="form login-form" onSubmit={handleLogin}>
<input autoFocus type="text" placeholder="username" aria-label="username" value={username} onChange={({target}) => setUsername(target.value)} />
<input type="password" placeholder="password" aria-label="password" value={password} onChange={({target}) => setPassword(target.value)} />
{error && (<p style={{color: 'red'}}>{error}</p>)}
<div className="form-action-container">
<div className="button-container">
<button disabled={invalid} className="form-button" type='submit'>Log In</button>
<p>Need an Account? <span><Link to={ROUTES.SIGN_UP}>Sign Up</Link></span></p>
</div>
<p>Forget your password? <span><Link to={ROUTES.RESET_PW}>Reset</Link></span></p>
</div>
</form>
</div>
</div>
)
}
The current problem is that the useEffect (or maybe the Auth method?) isn't updating the state and so the first time I click "login" in my login component, it returns 'null' from my protectedRoute component's as well as the main App component's console.log(user), returning null. Only after I refresh, does it change and let me get the user log as well as directed into the protectedRoute.
This is also true for my logOut scenario.
export default function Dashboard() {
const { Auth, Hub } = useContext(AmplifyContext);
const history = useHistory();
const handleLogOut = async (e) => {
e.preventDefault();
// amplify call to sign out
await Auth.signOut();
history.push(ROUTES.LOGIN);
}
return (
<div className="dashboard-container">
<h1>Welcome </h1>
<button onClick={handleLogOut}>log out</button>
</div>
)
}
I don't get logged out, nor do I get redirected unless I reload the page.
Why aren't the Auth.signOut() and the Auth.currentAuthenticatedUser() methods run like I want it to?
made her work a bit better after putting all auth related state into context provider and wrapping it around all {children} components and then using Hub to listen for changes to log out. (I had to stop using my route helper functions, so that's kind of a bummer. But it works at the moment. I will keep it as the solution). I had to use the amplify guideline for custom auth, so still not so satisfied...
Each related state variables that needs to be used in each component is using it from context (left it out for length).
// storing all state related to Authorization
import { createContext, useContext, useState } from "react";
import AmplifyContext from "./amplify";
const AuthContext = createContext();
function AuthContextProvider({ children }) {
const [formType, setFormType] = useState("signUp");
const [fullName, setFullName] = useState("");
const [username, setUsername] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [authCode, setAuthCode] = useState("");
const [error, setError] = useState("");
const [user, setUser] = useState(null);
const { Auth } = useContext(AmplifyContext);
let invalid;
const checkUser = async () => {
try {
const loggedInUser = await Auth.currentAuthenticatedUser();
setUser(loggedInUser);
console.log(user);
if (user) {
setFormType("dashboard");
} else {
setUser(null);
setFormType("login");
}
} catch (e) {
console.log(e.message);
}
};
const handleSignUp = async (e) => {
e.preventDefault();
try {
// amp auth signup. attribute must match (ie: if email is needed, state var needs to be called email (not other name))
await Auth.signUp({ username, password, attributes: { email } });
console.log("signed up");
setFullName("");
setUsername("");
setEmail("");
setPassword("");
setFormType("confirmSignUp");
} catch (e) {
console.log(e.message);
setError(e.message);
}
};
const handleConfirmAuthCode = async (e) => {
e.preventDefault();
try {
// amp auth confirm sign up
await Auth.confirmSignUp(username, authCode);
setFormType("login");
} catch (e) {
console.log(e.message);
setError(e.message);
}
};
const handleLogin = async (e) => {
e.preventDefault();
try {
// amplify Auth login
await Auth.signIn(username, password);
setUsername("");
setPassword("");
console.log("logged in");
setFormType("dashboard");
} catch (e) {
setError(e.message);
setPassword("");
}
};
const handleLogOut = async (e) => {
e.preventDefault();
// amplify call to sign out
await Auth.signOut();
//set some loading or redirect?
};
return (
<AuthContext.Provider
value={{
error,
setError,
handleSignUp,
checkUser,
handleConfirmAuthCode,
handleLogin,
handleLogOut,
fullName,
setFullName,
username,
setUsername,
email,
setEmail,
password,
setPassword,
formType,
setFormType,
authCode,
setAuthCode,
invalid,
user,
setUser,
}}
>
{children}
</AuthContext.Provider>
);
}
export { AuthContextProvider, AuthContext };
// top
ReactDOM.render(
<AmplifyContext.Provider value={{ Auth, Hub }}>
<AuthContextProvider>
<App />
</AuthContextProvider>
</AmplifyContext.Provider>,
document.getElementById("root")
);
// inside the App component (not yet finished)
import { useContext, useEffect } from "react";
import AmplifyContext from "./context/amplify";
import { AuthContext } from "./context/AuthContext";
import ConfirmSignUp from "./pages/confirmSignUp";
import Login from "./pages/login";
import SignUp from "./pages/sign-up";
import Dashboard from "./pages/dashboard";
import ResetPass from "./pages/reset-pw";
function App() {
const { Hub } = useContext(AmplifyContext);
const {
formType,
setFormType,
username,
setUsername,
error,
setError,
checkUser,
handleLogOut,
} = useContext(AuthContext);
async function setAuthListener() {
Hub.listen("auth", (data) => {
switch (data.payload.event) {
case "signIn":
console.log(`${username} signed in`);
break;
case "signOut":
console.log("user signed out");
setFormType("login");
break;
default:
break;
}
});
}
useEffect(() => {
checkUser();
setAuthListener();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
<>
{formType === "signUp" && <SignUp />}
{formType === "confirmSignUp" && <ConfirmSignUp />}
{formType === "login" && <Login />}
{formType === "dashboard" && (
<Dashboard handleLogOut={handleLogOut} />
)}
{formType === "reset" && (
<ResetPass />
)}
</>
);
}
export default App;
I'm trying to figure out the best way to create a global state variable that will hold a firebase authentication user id.
For example the below code would check if a user is logged in and then send them to welcome page if successful.
But I also need to setup up private routes on a different file, I want to be able to share the getId state. I read that useContext can do this but unsure how to implement it. Please advise, thanks
const [getId, setId] = useState("");
const login = async ( id ) => {
return setId(id);
};
firebase.auth().onAuthStateChanged((user) => {
if (user) {
login(user.uid).then(() => {
history.push("/welcome");
});
} else {
history.push("/");
}
});
const PrivateRoute = ({ getId, component: Component, ...rest }) => (
<Route
{...rest}
component={(props) =>
getId ? (
<div>
<Component {...props} />
</div>
) : (
<Redirect to="/" />
)
}
/>
);
I'll give you my example to have an Auth Context. Here are the parts:
The _app.js file:
import '../styles/globals.scss'
import { motion, AnimatePresence } from 'framer-motion'
import { useRouter } from 'next/router'
import Header from '../components/Header'
import Footer from '../components/Footer'
import { AuthProvider } from '../contexts/AuthContext'
import { CartProvider } from '../contexts/CartContext'
import { ThemeProvider } from '#material-ui/core'
import theme from '../styles/theme'
export default function App({ Component, pageProps }) {
const router = useRouter()
return(
<AnimatePresence exitBeforeEnter>
<CartProvider>
<AuthProvider>
<ThemeProvider theme={theme}>
<Header />
<motion.div key={router.pathname} className="main">
<Component { ...pageProps } />
<Footer />
</motion.div>
</ThemeProvider>
</AuthProvider>
</CartProvider>
</AnimatePresence>
)
}
The item of significance is the <AuthProvider> component. That's where the context is wrapped.
The AuthContent.js file:
import { createContext, useContext, useEffect, useState } from 'react'
import { auth } from '../firebase'
const AuthContext = createContext()
export function useAuth() {
return useContext(AuthContext)
}
export function AuthProvider({ children }) {
const [currentUser, setCurrentUser] = useState()
const [loading, setLoading] = useState(true)
function login(email, password) {
return auth.signInWithEmailAndPassword(email, password)
}
function signOut() {
return auth.signOut();
}
function signUp(email, password) {
return auth.createUserWithEmailAndPassword(email, password)
}
function getUser() {
return auth.currentUser
}
function isAdmin() {
return auth.currentUser.getIdTokenResult()
.then((idTokenResult) => {
if (!!idTokenResult.claims.admin) {
return true
} else {
return false
}
})
}
function isEditor() {
}
useEffect(() => {
const unsubscribe = auth.onAuthStateChanged(user => {
setCurrentUser(user)
setLoading(false)
})
return unsubscribe
}, [])
const value = {
currentUser,
getUser,
login,
signOut,
signUp
}
return (
<AuthContext.Provider value={value}>
{ !loading && children }
</AuthContext.Provider>
)
}
This is where the state is stored and accessed, including all of the helpers (signup, signout, login, etc).
How to use it:
import { Button, Card, CardHeader, CardContent, Link, TextField, Typography } from '#material-ui/core'
import { motion } from 'framer-motion'
import { useRef, useState } from 'react'
import { useAuth } from '../contexts/AuthContext'
import { useRouter } from 'next/router'
export default function SignupForm() {
const router = useRouter()
const { signUp } = useAuth()
const [state, setState] = useState({
email: "",
password: "",
passwordConfirm: ""
})
const [error, setError] = useState("")
function handleForm(e) {
setState({
...state,
[e.target.name]: e.target.value
})
}
async function handleSubmit(e) {
if (state.password !== state.passwordConfim) {
setError("Passwords do not match")
}
await signUp(state.email, state.password)
.catch(err => console.log(JSON.stringify(err)) )
router.push("/account")
}
return(
<motion.div>
<Card >
<CardHeader title="Header" />
<CardContent>
<TextField label="email" name="email" variant="outlined" onChange={ handleForm } />
<TextField label="password" name="password" type="password" variant="outlined" onChange={ handleForm } />
<TextField label="Password Confirmation" name="passwordConfirm" type="password" variant="outlined" onChange={ handleForm } />
{error && <Alert severity="error" variant="filled" >{error}</Alert>}
<Button onClick={ handleSubmit }>
<Typography variant="button">Sign Up</Typography>
</Button>
</CardContent>
</Card>
</motion.div>
)
}
You import { useAuth } from your context (I usually put mine in a context folder) and then you can invoke instances of the variables inside the component by destructuring (e.g. const { currentUser, login } = useAuth())