'React useContext keep data after redirect?
I wanna keep the username after login in a Context to access it later. The Context works fine but after redirecting the user to the Home the Context value is gone.
When i set the Context after the login is successfully, it works like it should..
Can someone tell me how to fix this?
Login.js
import { useContext, useState } from "react";
import { UserContext } from "../contexts/UserContext";
const { setUser, user } = useContext(UserContext);
async function handleLogin(e) {
e.preventDefault();
if (username && password) {
await fetch("http://localhost:5000/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "include",
body: JSON.stringify({
username: username,
password: password,
}),
})
.then((response) => response.json())
.then((data) => {
if (data.error) {
setLoginError(data.error);
return;
} else {
setUser(data);
console.log(user);
window.location.assign("/");
}
})
}
}
Home.js
import React, { useContext } from "react";
import { UserContext } from "../contexts/UserContext";
const Home = () => {
const { user } = useContext(UserContext);
return (
<>
<h1>Home</h1>
<p>{user.username}</p>
</>
);
};
export default Home;
App.js
import { Routes, Route } from "react-router-dom";
import { useState } from "react";
import IncludeLayout from "./helper/IncludeLayout";
import ExcludeLayout from "./helper/ExcludeLayout";
import ProtectedRoutes from "./helper/ProtectedRoutes";
import Home from "./pages/Home";
import Login from "./pages/Login";
import Users from "./pages/Users";
import { UserContext } from "./contexts/UserContext";
function App() {
const [user, setUser] = useState({});
return (
<ThemeProvider theme={theme}>
<UserContext.Provider value={{ user, setUser }}>
<Routes>
<Route element={<ExcludeLayout />}>
<Route exact path="login" element={<Login />} />
</Route>
<Route element={<ProtectedRoutes />}>
<Route element={<IncludeLayout />}>
<Route exact path="/" element={<Home />} />
<Route exact path="/users" element={<Users />} />
</Route>
</Route>
</Routes>
</UserContext.Provider>
</ThemeProvider>
);
}
export default App;
Solution 1:[1]
With help from Samathingamajig i figured out this solution that works for me:
import { useNavigate } from "react-router-dom";
const navi = useNavigate();
navi("/");
instead of using useHistory.
Solution 2:[2]
The reason it doesn't work is that you have not persisted the data to browser storage so when routed to another page the data will be lost there is no workaround it just persist the data or persist some kind of auth token so later you can check if there is token and if there is send it to the server to get the user detail if you do this using useEffct then save the data to the context it will work, you can have the useEffect in the app.js so that anytime a user routes to any page the useEffect will fire, if you want this functionality tell me and ill clarify more and alos show you how to do it.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Shark00n |
| Solution 2 | rediet yosef |
