From 43352113b8f13148ea546aa544ef7d8070b968d7 Mon Sep 17 00:00:00 2001 From: Jarda Snajdr Date: Fri, 17 Mar 2023 09:07:44 +0100 Subject: [PATCH] Create store lazily, console error on duplicate store --- packages/data/src/registry.js | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/packages/data/src/registry.js b/packages/data/src/registry.js index 899870b8d71be8..7a913da488f46e 100644 --- a/packages/data/src/registry.js +++ b/packages/data/src/registry.js @@ -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' ); } @@ -266,6 +270,8 @@ export function createRegistry( storeConfigs = {}, parent = null ) { // ignore it. } } + + return store; } /** @@ -274,7 +280,9 @@ 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 ) { @@ -282,7 +290,7 @@ export function createRegistry( storeConfigs = {}, parent = null ) { since: '5.9', alternative: 'wp.data.register( storeDescriptor )', } ); - registerStoreInstance( name, store ); + registerStoreInstance( name, () => store ); } /** @@ -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; }