Add useActions and useSelector hooks

[MAILPOET-2676]
This commit is contained in:
Amine Ben hammou
2020-03-05 00:31:25 +01:00
committed by amine-mp
parent 1d6a7f6fde
commit 9174df7323
5 changed files with 51 additions and 19 deletions

View File

@@ -1,26 +1,14 @@
import React from 'react';
import ReactDOM from 'react-dom';
import { useSelect, useDispatch } from '@wordpress/data';
import { initStore, STORE_NAME } from './store';
import { initStore } from './store';
import { useSelector, useActions } from './store/hooks';
const App = () => {
const isSaving = useSelect(
(sel) => sel(STORE_NAME).isSaving(),
[]
);
const error = useSelect(
(sel) => sel(STORE_NAME).getError(),
[]
);
const settings = useSelect(
(sel) => sel(STORE_NAME).getSettings(),
[]
);
const email = useSelect(
(sel) => sel(STORE_NAME).getSetting(['sender', 'address']),
[]
);
const actions = useDispatch(STORE_NAME);
const isSaving = useSelector('isSaving')();
const error = useSelector('getError')();
const settings = useSelector('getSettings')();
const email = useSelector('getSetting')(['sender', 'address']);
const actions = useActions();
const setEmail = (event) => {
actions.setSetting(['sender', 'address'], event.target.value);
};

View File

@@ -0,0 +1,2 @@
export * from './useActions';
export { default as useSelector } from './useSelector';

View File

@@ -0,0 +1,15 @@
/**
* Omits the first item in a tuple type
* Tail<[number, string, boolean]> gives [string, boolean]
*/
export type Tail<T extends any[]> =
((...args: T) => void) extends ((_: any, ...args: infer Others) => void) ? Others : never
/**
* Takes a function type and returns a new function
* type with same signature except the first parameter.
* ExcludeFirstParam<(x: number, y: string) => boolean>
* gives (y: string) => boolean
*/
export type ExcludeFirstParam<F extends ((...args: any[]) => any)> =
(...args: Tail<Parameters<F>>) => ReturnType<F>

View File

@@ -0,0 +1,13 @@
import { useDispatch } from '@wordpress/data';
import * as actions from '../actions';
import { STORE_NAME } from '..';
type Actions = typeof actions
export function useActions(): Actions {
return useDispatch(STORE_NAME);
}
export function useAction<Key extends keyof Actions>(key: Key): Actions[Key] {
return useDispatch(STORE_NAME)[key];
}

View File

@@ -0,0 +1,14 @@
import { useSelect } from '@wordpress/data';
import { STORE_NAME } from '..';
import * as selectors from '../selectors';
import { ExcludeFirstParam } from './types';
type Selectors = typeof selectors
export default function useSelector<Key extends keyof Selectors>(key: Key, deps: any[] = []):
ExcludeFirstParam<Selectors[Key]> {
return useSelect((select) => {
const selects = select(STORE_NAME);
return selects[key].bind(selects);
}, deps);
}