♻️ Provide cleaner sample for the store’s hooks

This commit is contained in:
Philipp Stracker 2025-02-05 16:27:19 +01:00
parent 60d747ea44
commit de24a30fac
No known key found for this signature in database

View file

@ -7,44 +7,51 @@
* @file * @file
*/ */
import { useDispatch } from '@wordpress/data'; import { useMemo } from '@wordpress/element';
import { useDispatch, useSelect } from '@wordpress/data';
import { createHooksForStore } from '../utils'; import { createHooksForStore } from '../utils';
import { STORE_NAME } from './constants'; 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 { useTransient, usePersistent } = createHooksForStore( STORE_NAME );
const { persist } = useDispatch( STORE_NAME );
// Read-only flags and derived state. return useMemo(
// Nothing here yet. () => ( {
select,
// Transient accessors. dispatch,
const [ isReady ] = useTransient( 'isReady' ); useTransient,
usePersistent,
// Persistent accessors. } ),
// TODO: Replace with real property. [ select, dispatch, useTransient, usePersistent ]
const [ sampleValue, setSampleValue ] = usePersistent( 'sampleValue' ); );
return {
persist,
isReady,
sampleValue,
setSampleValue,
};
}; };
export const useStore = () => { export const useStore = () => {
const { persist, isReady } = useHooks(); const { dispatch, useTransient } = useStoreData();
return { persist, isReady }; const [ isReady ] = useTransient( 'isReady' );
return { persist: dispatch.persist, isReady };
}; };
// TODO: Replace with real hook. // TODO: Replace with real hook.
export const useSampleValue = () => { export const useSampleValue = () => {
const { sampleValue, setSampleValue } = useHooks(); const { usePersistent, select } = useStoreData();
const [ sampleValue, setSampleValue ] = usePersistent( 'sampleValue' );
return { return {
sampleValue, sampleValue,
setSampleValue, setSampleValue,
flags: select.flags(),
}; };
}; };