Skip to content

Commit

Permalink
Create store lazily, console error on duplicate store
Browse files Browse the repository at this point in the history
  • Loading branch information
jsnajdr committed Mar 17, 2023
1 parent 3c41421 commit 4335211
Showing 1 changed file with 17 additions and 9 deletions.
26 changes: 17 additions & 9 deletions packages/data/src/registry.js
Original file line number Diff line number Diff line change
Expand Up @@ -211,14 +211,18 @@ export function createRegistry( storeConfigs = {}, parent = null ) {
/**
* Registers a store instance.
*
* @param {string} name Store registry name.
* @param {Object} store Store instance object (getSelectors, getActions, subscribe).
* @param {string} name Store registry name.
* @param {Function} createStore Function that creates a store object (getSelectors, getActions, subscribe).
*/
function registerStoreInstance( name, store ) {
function registerStoreInstance( name, createStore ) {
if ( stores[ name ] ) {
throw new Error( 'duplicate store oh no' );
// eslint-disable-next-line no-console
console.error( 'Store "' + name + '" is already registered.' );
return stores[ name ];
}

const store = createStore();

if ( typeof store.getSelectors !== 'function' ) {
throw new TypeError( 'store.getSelectors must be a function' );
}
Expand Down Expand Up @@ -266,6 +270,8 @@ export function createRegistry( storeConfigs = {}, parent = null ) {
// ignore it.
}
}

return store;
}

/**
Expand All @@ -274,15 +280,17 @@ export function createRegistry( storeConfigs = {}, parent = null ) {
* @param {StoreDescriptor} store Store descriptor.
*/
function register( store ) {
registerStoreInstance( store.name, store.instantiate( registry ) );
registerStoreInstance( store.name, () =>
store.instantiate( registry )
);
}

function registerGenericStore( name, store ) {
deprecated( 'wp.data.registerGenericStore', {
since: '5.9',
alternative: 'wp.data.register( storeDescriptor )',
} );
registerStoreInstance( name, store );
registerStoreInstance( name, () => store );
}

/**
Expand All @@ -298,10 +306,10 @@ export function createRegistry( storeConfigs = {}, parent = null ) {
throw new TypeError( 'Must specify store reducer' );
}

const store = createReduxStore( storeName, options ).instantiate(
registry
const store = registerStoreInstance( storeName, () =>
createReduxStore( storeName, options ).instantiate( registry )
);
registerStoreInstance( storeName, store );

return store.store;
}

Expand Down

0 comments on commit 4335211

Please sign in to comment.