Skip to content

Commit 1e3dfdc

Browse files
committed
initialize the state, fixes #3
1 parent b97b6aa commit 1e3dfdc

File tree

3 files changed

+20
-3
lines changed

3 files changed

+20
-3
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,8 @@ You can pass a config object to `syncedReducer`.
4242
option | default | description
4343
--------------- | ----------- | ------------
4444
**name** | `reducer.toString()` | Pass a custom name for the reducer.<br>See [why you might need this](#when-using-multiple-different-syncedreducers-all-receive-the-same-state).
45-
**skipReducer** | `false` | When the internal action is dispatched, it will call your own reducer with the new value. You can skip this by setting `skipReducer` to `true`.
45+
**skipReducer** | `false` | When the state is changed in another tab, it will call your own reducer with the new value. You can skip this by setting `skipReducer` to `true`.
46+
**skipLoading** | `false` | Do not initialize the state with the last value stored in localStorage.
4647

4748
## Common issues
4849

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "redux-sync-reducer",
3-
"version": "0.0.2",
3+
"version": "0.0.3",
44
"description": "High order reducer to sync partial states between tabs",
55
"main": "lib/index.js",
66
"scripts": {

src/index.js

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ const isSupported = !!(window && window.localStorage);
1111
*/
1212
const syncedReducers = [];
1313

14+
const LOAD = '@@sync-reducer/init';
1415

1516
/**
1617
* Get the type of the action.
@@ -49,14 +50,26 @@ export function syncedReducer(reducer, config = {}) {
4950
const name = config.name || reducer.toString();
5051
const actionType = getActionType(name);
5152

53+
let isLoaded = !!config.skipLoading;
54+
5255
syncedReducers.push(name);
5356

5457
return (state, action = {}, ...slices) => {
5558
switch(action.type) {
5659
case actionType:
5760
return config.skipReducer ? action.payload : reducer(action.payload, action, ...slices);
61+
case LOAD:
62+
if(!isLoaded) {
63+
isLoaded = true;
64+
return isSupported
65+
? JSON.parse(localStorage.getItem(getKeyName(name))) || state
66+
: state;
67+
}
68+
// fallthrough to default case if the state is already loaded
5869
default:
59-
return sync(name, reducer(state, action, ...slices));
70+
return isLoaded
71+
? sync(name, reducer(state, action, ...slices))
72+
: reducer(state, action, ...slices);
6073
}
6174
}
6275
}
@@ -80,5 +93,8 @@ export const syncMiddleware = store => {
8093
})
8194
});
8295

96+
// load all existing states from localStorage
97+
store.dispatch({ type: LOAD });
98+
8399
return next => action => next(action);
84100
}

0 commit comments

Comments
 (0)