I am saving jwt token returned from my backend app, after Login as shown below:
const login = (event) => {
event.preventDefault();
postWithoutAuth("/auth/login", formValues, enqueueSnackbar)
.then((response) => {
localStorage.setItem("currentUser", response.data.id);
localStorage.setItem("username", response.data.username);
localStorage.setItem("tokenKey", response.data.token);
localStorage.setItem("roles", JSON.stringify(response.data.roles));
navigate("/");
// window.location.reload(true);
})
};
And then navigate to home page. At this step, all the set values are present in the localStorage.
But, when I click any list menu and retrieve data, the request hit to backend app does not have jwt value. On the other hand, if I refresh the page after login (as you see in the login methoıd (// window.location.reload(true);
), there is no problem.
Now, the only thing I need, to make the frontend app avare of the localStorage values when I navigate to Home page after login. So, how can I do that?
Here is my list method:
useEffect(() => {
fetchData();
}, []);
const fetchData = () => {
const userId = localStorage.getItem("currentUser");
getWithAuth("/users/")
.then((response) => {
setData(response.data);
})
};
Update-II: Here is the problematic part where jwt is retrieved and pass to the request as axios config:
const AUTH_TOKEN = localStorage.getItem("tokenKey");
const config = {
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Credentials": true,
"Content-Type": "application/json",
Accept: "application/json",
Authorization: `Bearer ${AUTH_TOKEN}`
},
};
export const getWithAuth = (url) => {
const request = axios.get(url, config);
return request.then((response) => response.data);
};