From de24a30fac4577483ee64448d074cf0c254bed73 Mon Sep 17 00:00:00 2001 From: Philipp Stracker Date: Wed, 5 Feb 2025 16:27:19 +0100 Subject: [PATCH] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20Provide=20cleaner=20sample?= =?UTF-8?q?=20for=20the=20store=E2=80=99s=20hooks?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../resources/js/data/_example/hooks.js | 51 +++++++++++-------- 1 file changed, 29 insertions(+), 22 deletions(-) diff --git a/modules/ppcp-settings/resources/js/data/_example/hooks.js b/modules/ppcp-settings/resources/js/data/_example/hooks.js index 95db3765e..21253d137 100644 --- a/modules/ppcp-settings/resources/js/data/_example/hooks.js +++ b/modules/ppcp-settings/resources/js/data/_example/hooks.js @@ -7,44 +7,51 @@ * @file */ -import { useDispatch } from '@wordpress/data'; +import { useMemo } from '@wordpress/element'; +import { useDispatch, useSelect } from '@wordpress/data'; import { createHooksForStore } from '../utils'; import { STORE_NAME } from './constants'; -const useHooks = () => { +/** + * Single source of truth for access Redux details. + * + * This hook returns a stable API to access actions, selectors and special hooks to generate + * getter- and setters for transient or persistent properties. + * + * @return {{select, dispatch, useTransient, usePersistent}} Store data API. + */ +const useStoreData = () => { + const select = useSelect( ( selectors ) => selectors( STORE_NAME ), [] ); + const dispatch = useDispatch( STORE_NAME ); const { useTransient, usePersistent } = createHooksForStore( STORE_NAME ); - const { persist } = useDispatch( STORE_NAME ); - // Read-only flags and derived state. - // Nothing here yet. - - // Transient accessors. - const [ isReady ] = useTransient( 'isReady' ); - - // Persistent accessors. - // TODO: Replace with real property. - const [ sampleValue, setSampleValue ] = usePersistent( 'sampleValue' ); - - return { - persist, - isReady, - sampleValue, - setSampleValue, - }; + return useMemo( + () => ( { + select, + dispatch, + useTransient, + usePersistent, + } ), + [ select, dispatch, useTransient, usePersistent ] + ); }; export const useStore = () => { - const { persist, isReady } = useHooks(); - return { persist, isReady }; + const { dispatch, useTransient } = useStoreData(); + const [ isReady ] = useTransient( 'isReady' ); + + return { persist: dispatch.persist, isReady }; }; // TODO: Replace with real hook. export const useSampleValue = () => { - const { sampleValue, setSampleValue } = useHooks(); + const { usePersistent, select } = useStoreData(); + const [ sampleValue, setSampleValue ] = usePersistent( 'sampleValue' ); return { sampleValue, setSampleValue, + flags: select.flags(), }; };