Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/forty-files-help.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@modern-js-reduck/store': patch
---

fix: fix initial state missing
39 changes: 37 additions & 2 deletions packages/store/src/store/createStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ import {
applyMiddleware,
compose,
createStore as createReduxStore,
Reducer,
StoreEnhancerStoreCreator,
type Action,
type Reducer,
type StoreEnhancer,
type StoreEnhancerStoreCreator,
} from 'redux';
import { createContext } from './context';
import type { Context, StoreConfig } from '@/types';
Expand Down Expand Up @@ -31,6 +33,7 @@ const createStore = (props: StoreConfig = {}): Context['store'] => {
initialState,
compose<StoreEnhancerStoreCreator<unknown>>(
...[
mergeInitialState(),
middlewares ? applyMiddleware(...middlewares) : undefined,
...(enhancers || []),
].filter(Boolean),
Expand All @@ -50,4 +53,36 @@ const createStore = (props: StoreConfig = {}): Context['store'] => {
return store;
};

/**
* Merge prev global state when mounting new models
* to avoid to miss the initial state of the mounting models
*/
function mergeInitialState(): StoreEnhancer {
return createStore => (reducer, initialState) => {
const liftReducer = (r: Reducer) => {
if (typeof r !== 'function') {
throw new Error('Expected the reducer to be a function.');
}

return (state = initialState, action: Action) => {
const nextState = r(state, action);
if (/^@@redux\/REPLACE/.test(action.type)) {
return { ...state, ...nextState };
} else {
return nextState;
}
};
};

const store = createStore(liftReducer(reducer));

return {
...store,
replaceReducer: reducer => {
return store.replaceReducer(liftReducer(reducer));
},
};
};
}

export default createStore;