score:4
Issue
React hooks don't share state.
Solution
Move the useAuth
state into a React context and provide that to the app. The useAuth
hook should then use the useContext
hook to access the single auth state.
Example:
Create an AuthContext
, provider, and hook.
import { createContext, useContext, useEffect, useState } from 'react';
const AuthContext = createContext({
auth: null,
setAuth: () => {},
user: null,
});
export useAuth = () => useContext(AuthContext);
const AuthProvider = ({ children }) => {
const [auth, setAuth] = useState(null);
const [user, setUser] = useState(null);
useEffect(() => {
const isAuth = async () => {
try {
const res await axios.get(
'http://localhost:5000/api/logged-user/',
{ withCredentials: true }
);
setUser(res.data);
} catch(error) {
setUser(null);
};
};
isAuth();
}, [auth]);
return (
<AuthContext.Provider value={{ auth, setAuth, user }}>
{children}
</AuthContext.Provider>
);
};
export default AuthProvider;
Wrap the App
component with the AuthProvider
component.
import AuthProvider from "../path/to/AuthContext";
...
<AuthProvider>
<App />
</AuthProvider>
Now that there's a single auth
and user
state the useAuth
hooks all reference the same state.
App
function App() {
const { auth } = useAuth();
return (
<Router>
{auth ? <Navbar /> : <NotAuthNavbar />}
<Routes>
<Route path="/" element={<Dashboard />} />
<Route path="/login" element={<Login />} />
<Route path="/signup" element={<Register />} />
<Route
path="/profile"
element={(
<PrivateRoute>
<Profile />
</PrivateRoute>
)}
/>
<Route path="/confirm-register/:tokenConfirm" element={<ConfirmRegister />} />
<Route path="/registered" element={<RegisterMessage />} />
</Routes>
</Router>
);
}
Navbar
Access the setAuth
updater function to set auth
false upon successful logout.
const Navbar = () => {
const { setAuth, user } = useAuth();
const navigate = useNavigate();
const logout = async () => {
const res await axios.get(
"http://localhost:5000/api/logout/",
{ withCredentials: true }
);
console.log(res.data);
setAuth(false);
navigate('/login');
}
return(
<section>
<div className="navbar">
<ul className="navbar-menu">
<li><Link to={"/dashboard"}>Dashboard</Link></li>
<li><Link to={"/profile"}>Welcome {user.username}</Link></li>
<li><button type='button' onClick={logout}>Logout</button></li>
</ul>
</div>
<Outlet />
</section>
);
};
Component using login
function
Use the useAuth
hook to access the setAuth
updater function and set auth
true upon successful authentication.
const { setAuth } = useAuth();
...
const login = async (e) => {
e.preventDefault();
try {
const res = await axios.post(
"http://localhost:5000/api/signin/",
{
email: email.email,
password: password.password
},
{
withCredentials: true,
}
);
if (res.status === 200) {
alert('!LOGGED');
setAuth(true);
navigate('/profile');
}
} catch(error) {
setHandleErrors(JSON.parse(error.request.response));
} finally {
setIsSubmitted(true);
}
}
Note: It's anti-pattern to mix async/await
with Promise chains. Generally you should select one or the other. I've used async/await
with try/catch
to handle rejected promises and other errors that may occur.
Source: stackoverflow.com
Related Query
- Update navbar after success login or logout redirection
- How we can update the state of button to logout after successfull login in react redux
- Redirect to previous route after a login success
- React change login link to logout after login
- Why navbar components doesn't update after user logs in? (no Redux)
- How to update the state of new context provider after ajax success
- react router v6 won't switch to Home Page after Login Page: Warning: Can't perform a React state update on an unmounted component
- How to redirect to log in page after click logout button on navbar header in React?
- React Router - Structure NavBar Before Login and after Login
- how to sync pages after logout and login on one of them?
- Login Logout in Navbar
- Reactjs routing to home page after login success
- ReactJS: Page update after login
- How to display username on navbar after login in react redux
- How do I get the result from login action to check in another component Menu after login success
- Logging old user data on login after logout in react using JWT
- How to update my UseEffect component to render new UI after a successful user login
- How to update side menu item list in an ionic react app after login
- How to update login data into state after changing pathname in reactjs
- React doesn't update the view after login
- Blank page after login redirection React.js
- Maximum update depth exceeded. After Login Using Context And Hooks
- Change data on navbar when logout and login with another account
- Toggle login logout not working in react js, when we refresh page then it is not working (means Navbar Components not changing)
- after logging in my 2nd action is not getting dispatch after login success action
- Initialstate not updated after success login
- Redirection to dashboard after login in react
- Automatic redirect after login with react-router
- Nextjs: TypeError: unsupported file type: undefined after update to v.11
- How to hide navbar in login page in react router
More Query from same tag
- How do I add user inputs on click?
- Draft.js Inserting Immutable Entity
- Changing a Class String variable through another Class - Not working
- Loading and running Javascript modules depending on current page
- react-app-rewired requiring giving mini-css-extract-plugin
- Getting empty state after calling the handleSubmit event from setInterval function
- Passing a Click Event to Child
- TypeError: Cannot read property 'then' of undefined in react js
- Concat Arrays in React/JavaScript via prevState
- Autocomplete filter in react ant-design
- Why are Google Map drawing controls appearing twice?
- Multiple select input by "Unique Select" with JSON Schema Form (Retool)
- Applying Classes Conditionally in React
- Union types with TypeScript and React
- How to add 'a' link tag with hyperlink in Reactjs app
- Unable to use switch toggle for dark mode in material-ui
- Delay Auth0 redirect in React until after user credentials have been received
- How to change title of page when page is redirected using router in reactjs?
- How to force client redirect to login page with express post request?
- Uploading a file using "fetch" in reactJS
- How to pass a specific prop when the props can have multiple types in React, Typescript?
- How to push route onClick in list React
- Why children component with redux-form doesn't re-render?
- How to add styles to an unknown child in React with Material-UI?
- React-Bootstrap I can't get Alert to appear when checking if user email is verified
- React scroll position after render when scrollTop is zero
- How to get index of nested row in antd?
- Redux - Dispatching Actions Correctly
- Render 2 columns using map in react
- How to fetch data only when the modal loads