♻️ Convert todo-store hooks to new code pattern

This commit is contained in:
Philipp Stracker 2025-02-17 13:33:00 +01:00
parent 1bebfe5e62
commit e5f83756ab
No known key found for this signature in database

View file

@ -10,6 +10,31 @@
import { useSelect, useDispatch } from '@wordpress/data';
import { STORE_NAME } from './constants';
import { createHooksForStore } from '../utils';
import { useMemo } from '@wordpress/element';
/**
* 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 );
return useMemo(
() => ( {
select,
dispatch,
useTransient,
usePersistent,
} ),
[ select, dispatch, useTransient, usePersistent ]
);
};
const ensureArray = ( value ) => {
if ( ! value ) {
@ -19,12 +44,8 @@ const ensureArray = ( value ) => {
};
const useHooks = () => {
const { useTransient } = createHooksForStore( STORE_NAME );
const { fetchTodos, setDismissedTodos, setCompletedTodos, persist } =
useDispatch( STORE_NAME );
// Read-only flags and derived state.
const [ isReady ] = useTransient( 'isReady' );
const { dispatch } = useStoreData();
const { fetchTodos, setDismissedTodos, setCompletedTodos } = dispatch;
// Get todos data from store
const { todos, dismissedTodos, completedTodos } = useSelect( ( select ) => {
@ -62,8 +83,6 @@ const useHooks = () => {
);
return {
persist,
isReady,
todos: filteredTodos,
dismissedTodos,
completedTodos,
@ -74,8 +93,11 @@ const useHooks = () => {
};
export const useStore = () => {
const { persist, isReady } = useHooks();
return { persist, isReady };
const { dispatch, useTransient } = useStoreData();
const { persist, refresh } = dispatch;
const [ isReady ] = useTransient( 'isReady' );
return { persist, refresh, isReady };
};
export const useTodos = () => {