Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you, or should you use localStorage in Redux's initial state?

For example...

export const user = (state = {   id: localStorage.getItem('id'),   name: localStorage.getItem('name'),   loggedInAt: null }, action) => {     case types.LOGIN:       localStorage.setItem('name', action.payload.user.name);       localStorage.setItem('id', action.payload.user.id);       return { ...state, ...action.payload.user }      default:       return {  ...state, loggedInAt: Date.now() } } 

That's a scaled down version of what I'm doing, default returns the state from localStorage as expected. However the state of my application is actually blank once I refresh the page.

like image 827
Ewan Valentine Avatar asked Apr 12 '16 18:04

Ewan Valentine


People also ask

When should you use local storage?

To keep it short, here's the only situation in which you should use local storage: when you need to store some publicly available information that is not at all sensitive, doesn't need to be used in a high performance app, isn't larger than 5MB, and consists of purely string data.

Does redux use localStorage?

The redux store contains total, amount, and cart items. This store's state will be later saved in the local storage.

Where is redux store saved?

It's stored in browser's memory.

What is the difference between local storage and redux store?

In simple Words, Local storage provided by browser and data stored can be access in browser only. where as Redux is State management Library, data can be stored in state and handled by redux.


1 Answers

Redux createStore 2nd param is intended for store initialization:

createStore(reducer, [initialState], [enhancer]) 

So you can do something like this:

const initialState = {   id: localStorage.getItem('id'),   name: localStorage.getItem('name'),   loggedInAt: null };  const store = createStore(mainReducer, initialState); 

Since reducers should be pure functions (i.e. no side effects) and localStorage.setItem is a side effect, you should avoid saving to localStorage in a reducer.

Instead you can:

store.subscribe(() => {     const { id, name } = store.getState();      localStorage.setItem('name', name);     localStorage.setItem('id', id); }); 

This will happen whenever the state changes, so it might affect performance.

Another option is to save the state only when the page is closed (refresh counts) using onBeforeUnload:

window.onbeforeunload = () => {     const { id, name } = store.getState();      localStorage.setItem('name', name);     localStorage.setItem('id', id); }; 
like image 169
Ori Drori Avatar answered Sep 28 '22 11:09

Ori Drori