Reputation: 2081
I currently have an application using redux and I have it set that every time the app loads it checks the JWT token is valid and adds the user data to the state.
I was wondering what the differences are between calling the api and then storing data in the state every reload or storing the data once in localStorage
?
How the code is setup with calling the api and storing with redux.
CHECK TOKEN
const token = localStorage.UserIdToken;
if (token) {
const decodedToken = jwtDecode(token);
if (decodedToken.exp * 1000 < Date.now()) {
store.dispatch(logoutUser());
} else {
store.dispatch({ type: SET_AUTHENTICATED });
axios.defaults.headers.common['Authorization'] = token;
store.dispatch(getUserData());
}
}
getUserData()
export const getUserData = () => async dispatch => {
try {
const res = await axios.get('/user');
dispatch({
type: SET_USER,
payload: res.data,
});
}
...
};
Upvotes: 1
Views: 1176
Reputation: 1862
First of all, storing the data once in localStorage
means that the user will not receive updates to his data, but will always receive the same. Think of seeing the same social media feed every time you log in, which would be the case if it would be saved in localStorage
and not requested from the api every reload.
Second, storing data in localStorage
instead of the redux state means you use the benefits of using state and redux - redux ensures that components will rerender when state they depend on changes. This ensures that components are responsive to user actions. localStorage
won't do that.
Following your comment, I think there is another reason you should consider:
Using localStorage
might pose problems if you want to change the user data (add a field for instance). If the data was in 1 place, you could change all user data and let users pull the new data on the next reload. If the data is in localStorage
, you will need to add code to your app that will change the existing data on first reload, and then do nothing on other times. This is not a good pattern, and has a better chance of having bugs and problems.
Upvotes: 1