I am getting an state value i.e loggedIn user name then printing loggedIn user name on my page. But when I refresh my page then the state value is lost.
I am creating state value using redux.
This is my action.js -
// Login - get user token
export const loginUser = userData => dispatch => {
axios
.post("http://localhost:5000/login", userData)
.then(res => {
// Save to localStorage
// Set token to localStorage
const { token } = res.data;
localStorage.setItem("usertoken", token);
// Set token to Auth header
setAuthToken(token);
// Decode token to get user data
const decoded = jwt_decode(token);
// Set current user
dispatch(setCurrentUser(decoded));
})
.catch(err => {
return err;
}
);
};
// Set logged in user
export const setCurrentUser = decoded => {
return {
type: SET_CURRENT_USER,
payload: decoded
};
};
// User loading
export const setUserLoading = () => {
return {
type: USER_LOADING
};
};
// Log user out
export const logoutUser = () => dispatch => {
// Remove token from local storage
localStorage.removeItem("usertoken");
// Remove auth header for future requests
setAuthToken(false);
// Set current user to empty object {} which will set isAuthenticated to false
dispatch(setCurrentUser({}));
};
this is my reducer.js -
import {
SET_CURRENT_USER,
USER_LOADING
} from "../Actions/actions";
const isEmpty = require("is-empty");
const initialState = {
isAuthenticated: false,
user: {},
loading: false
};
export default function (state = initialState, action) {
switch (action.type) {
case SET_CURRENT_USER:
return {
...state,
isAuthenticated: !isEmpty(action.payload),
user: action.payload
};
case USER_LOADING:
return {
...state,
loading: true
};
default:
return state;
}
}
and in header.js I am printing loggedIn user name.
const userLink = () => (
<div className="" style={{ display: "inline-flex" }}>
<li class="nav-item">
<Link className="nav-link" to="/">
{user.name}
</Link>
</li>
<li class="nav-item">
<a href="" onClick={this.logOut.bind(this)} className="nav-link">
Logout
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/">
AboutUs
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/">
ContactUs
</a>
</li>
</div>
);
I am getting loggedIn user name in state. but hen I am refreshing the page the state value of loggedIn user name is lost. One more thing I am including Header.js file in all pages of my react Application.
How can I save my state value of loggedIn user from any losses if I refresh the page ?
localStorage, how you are storing localStorage value in state?