From b0b10cafa67f36bbae055d21ec75eddc048967ac Mon Sep 17 00:00:00 2001 From: Jon Surrell Date: Fri, 14 Feb 2020 00:21:16 +0100 Subject: [PATCH] wordpress__data: Add unsubscribe return to subscribe (#42355) * Add unsubscribe to subscribe * Add subscribe/unsubscribe test --- types/wordpress__data/index.d.ts | 21 ++++++++++++++++++- .../wordpress__data/wordpress__data-tests.tsx | 3 +++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/types/wordpress__data/index.d.ts b/types/wordpress__data/index.d.ts index f4a2fc2f57..c93d6b9ae1 100644 --- a/types/wordpress__data/index.d.ts +++ b/types/wordpress__data/index.d.ts @@ -18,10 +18,29 @@ export { Action, combineReducers }; // export type SelectorMap = Record(...args: readonly any[]) => T>; export type DispatcherMap = Record(...args: readonly any[]) => T>; -export type Subscriber = (callback: () => void) => void; + +/** + * Subscribe to any changes to the store + * + * @param callback Will be invoked whenever there are any updates to the store. + * @returns A callback that can be invoked to unsubscribe. + * + * @example + * + * const unsubscribe = subscribe( () => { + * // You could use this opportunity to test whether the derived result of a + * // selector has subsequently changed as the result of a state update. + * } ); + * + * // Later, if necessary... + * unsubscribe(); + * + */ +export type Subscriber = (callback: () => void) => () => void; export function dispatch(key: string): DispatcherMap; export function select(key: string): SelectorMap; + export const subscribe: Subscriber; // diff --git a/types/wordpress__data/wordpress__data-tests.tsx b/types/wordpress__data/wordpress__data-tests.tsx index 19cb257652..17c15c2f17 100644 --- a/types/wordpress__data/wordpress__data-tests.tsx +++ b/types/wordpress__data/wordpress__data-tests.tsx @@ -3,6 +3,9 @@ import * as data from '@wordpress/data'; data.select('core/block-editor').isTyping(); data.dispatch('core/block-editor').resetBlocks(''); +const unsubscribe = data.subscribe(() => console.log('Store was updated.')); +unsubscribe(); + data.use(data.plugins.persistence, { storage: window.localStorage }); interface FooBar {