Skip to content

Commit

Permalink
@wordpress/data: Introduce useSelect custom hook. (#15737)
Browse files Browse the repository at this point in the history
A new `useSelect` hook for the `wp.data` api!  This hook allows for an alternative way to interact with data kept in a store state via registered selectors following a similar pattern to `useEffect` and other react hooks.

Other notable changes in this pull:

- exposing the custom `useRegistry` react hook for retrieving the `registry` object from components in a registry provider tree.
- `withSelect` implements `useSelect` under the hood.

Many thanks also to @epiqueras for contributions to the work in this pull.
  • Loading branch information
nerrad authored May 27, 2019
1 parent 700121d commit ce78cd8
Show file tree
Hide file tree
Showing 15 changed files with 875 additions and 338 deletions.
10 changes: 10 additions & 0 deletions packages/data/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,13 @@
## Master

### New Feature

- Expose `useSelect` hook for usage in functional components. ([#15737](https://github.com/WordPress/gutenberg/pull/15737))

### Enhancements

- `withSelect` internally uses the new `useSelect` hook. ([#15737](https://github.com/WordPress/gutenberg/pull/15737). **Note:** This _could_ impact performance of code using `withSelect` in edge-cases. To avoid impact, memoize passed in `mapSelectToProps` callbacks or implement `useSelect` directly with dependencies.

## 4.5.0 (2019-05-21)

### Bug Fix
Expand Down
130 changes: 125 additions & 5 deletions packages/data/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -379,25 +379,57 @@ _Returns_

<a name="RegistryConsumer" href="#RegistryConsumer">#</a> **RegistryConsumer**

Undocumented declaration.
A custom react Context consumer exposing the provided `registry` to
children components. Used along with the RegistryProvider.

You can read more about the react context api here:
<https://reactjs.org/docs/context.html#contextprovider>

_Usage_

````js
const {
RegistryProvider,
RegistryConsumer,
createRegistry
} = wp.data;

const registry = createRegistry( {} );

const App = ( { props } ) => {
return <RegistryProvider value={ registry }>
<div>Hello There</div>
<RegistryConsumer>
{ ( registry ) => (
<ComponentUsingRegistry
{ ...props }
registry={ registry }
) }
</RegistryConsumer>
</RegistryProvider>
}

<a name="RegistryProvider" href="#RegistryProvider">#</a> **RegistryProvider**

Undocumented declaration.
A custom Context provider for exposing the provided `registry` to children
components via a consumer.

See <a name="#RegistryConsumer">RegistryConsumer</a> documentation for
example.

<a name="select" href="#select">#</a> **select**

Given the name of a registered store, returns an object of the store's selectors.
The selector functions are been pre-bound to pass the current state automatically.
As a consumer, you need only pass arguments of the selector, if applicable.
_Usage_
*Usage*
```js
const { select } = wp.data;
select( 'my-shop' ).getPrice( 'hammer' );
```
````
_Parameters_
Expand Down Expand Up @@ -435,6 +467,91 @@ _Parameters_

Undocumented declaration.

<a name="useRegistry" href="#useRegistry">#</a> **useRegistry**

A custom react hook exposing the registry context for use.

This exposes the `registry` value provided via the
<a href="#RegistryProvider">Registry Provider</a> to a component implementing
this hook.

It acts similarly to the `useContext` react hook.

Note: Generally speaking, `useRegistry` is a low level hook that in most cases
won't be needed for implementation. Most interactions with the wp.data api
can be performed via the `useSelect` hook, or the `withSelect` and
`withDispatch` higher order components.

_Usage_

```js
const {
RegistryProvider,
createRegistry,
useRegistry,
} = wp.data

const registry = createRegistry( {} );

const SomeChildUsingRegistry = ( props ) => {
const registry = useRegistry( registry );
// ...logic implementing the registry in other react hooks.
};


const ParentProvidingRegistry = ( props ) => {
return <RegistryProvider value={ registry }>
<SomeChildUsingRegistry { ...props } />
</RegistryProvider>
};
```

_Returns_

- `Function`: A custom react hook exposing the registry context value.

<a name="useSelect" href="#useSelect">#</a> **useSelect**

Custom react hook for retrieving props from registered selectors.

In general, this custom React hook follows the
[rules of hooks](https://reactjs.org/docs/hooks-rules.html).

_Usage_

```js
const { useSelect } = wp.data;
function HammerPriceDisplay( { currency } ) {
const price = useSelect( ( select ) => {
return select( 'my-shop' ).getPrice( 'hammer', currency )
}, [ currency ] );
return new Intl.NumberFormat( 'en-US', {
style: 'currency',
currency,
} ).format( price );
}
// Rendered in the application:
// <HammerPriceDisplay currency="USD" />
```

In the above example, when `HammerPriceDisplay` is rendered into an
application, the price will be retrieved from the store state using the
`mapSelect` callback on `useSelect`. If the currency prop changes then
any price in the state for that currency is retrieved. If the currency prop
doesn't change and other props are passed in that do change, the price will
not change because the dependency is just the currency.
_Parameters_
- _\_mapSelect_ `Function`: Function called on every state change. The returned value is exposed to the component implementing this hook. The function receives the `registry.select` method on the first argument and the `registry` on the second argument.
- _deps_ `Array`: If provided, this memoizes the mapSelect so the same `mapSelect` is invoked on every state change unless the dependencies change.
_Returns_
- `Function`: A custom react hook.
<a name="withDispatch" href="#withDispatch">#</a> **withDispatch**
Higher-order component used to add dispatch props using registered action creators.
Expand Down Expand Up @@ -545,7 +662,10 @@ const HammerPriceDisplay = withSelect( ( select, ownProps ) => {
// <HammerPriceDisplay currency="USD" />
```

In the above example, when `HammerPriceDisplay` is rendered into an application, it will pass the price into the underlying `PriceDisplay` component and update automatically if the price of a hammer ever changes in the store.
In the above example, when `HammerPriceDisplay` is rendered into an
application, it will pass the price into the underlying `PriceDisplay`
component and update automatically if the price of a hammer ever changes in
the store.

_Parameters_

Expand Down
12 changes: 12 additions & 0 deletions packages/data/src/components/async-mode-provider/context.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/**
* WordPress dependencies
*/
import { createContext } from '@wordpress/element';

export const Context = createContext( false );

const { Consumer, Provider } = Context;

export const AsyncModeConsumer = Consumer;

export default Provider;
12 changes: 2 additions & 10 deletions packages/data/src/components/async-mode-provider/index.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,2 @@
/**
* WordPress dependencies
*/
import { createContext } from '@wordpress/element';

const { Consumer, Provider } = createContext( false );

export const AsyncModeConsumer = Consumer;

export default Provider;
export { default as useAsyncMode } from './use-async-mode';
export { default as AsyncModeProvider, AsyncModeConsumer } from './context';
13 changes: 13 additions & 0 deletions packages/data/src/components/async-mode-provider/use-async-mode.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
/**
* WordPress dependencies
*/
import { useContext } from '@wordpress/element';

/**
* Internal dependencies
*/
import { Context } from './context';

export default function useAsyncMode() {
return useContext( Context );
}
54 changes: 54 additions & 0 deletions packages/data/src/components/registry-provider/context.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/**
* WordPress dependencies
*/
import { createContext } from '@wordpress/element';

/**
* Internal dependencies
*/
import defaultRegistry from '../../default-registry';

export const Context = createContext( defaultRegistry );

const { Consumer, Provider } = Context;

/**
* A custom react Context consumer exposing the provided `registry` to
* children components. Used along with the RegistryProvider.
*
* You can read more about the react context api here:
* https://reactjs.org/docs/context.html#contextprovider
*
* @example
* ```js
* const {
* RegistryProvider,
* RegistryConsumer,
* createRegistry
* } = wp.data;
*
* const registry = createRegistry( {} );
*
* const App = ( { props } ) => {
* return <RegistryProvider value={ registry }>
* <div>Hello There</div>
* <RegistryConsumer>
* { ( registry ) => (
* <ComponentUsingRegistry
* { ...props }
* registry={ registry }
* ) }
* </RegistryConsumer>
* </RegistryProvider>
* }
*/
export const RegistryConsumer = Consumer;

/**
* A custom Context provider for exposing the provided `registry` to children
* components via a consumer.
*
* See <a name="#RegistryConsumer">RegistryConsumer</a> documentation for
* example.
*/
export default Provider;
17 changes: 2 additions & 15 deletions packages/data/src/components/registry-provider/index.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,2 @@
/**
* WordPress dependencies
*/
import { createContext } from '@wordpress/element';

/**
* Internal dependencies
*/
import defaultRegistry from '../../default-registry';

const { Consumer, Provider } = createContext( defaultRegistry );

export const RegistryConsumer = Consumer;

export default Provider;
export { default as RegistryProvider, RegistryConsumer } from './context';
export { default as useRegistry } from './use-registry';
52 changes: 52 additions & 0 deletions packages/data/src/components/registry-provider/use-registry.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/**
* WordPress dependencies
*/
import { useContext } from '@wordpress/element';

/**
* Internal dependencies
*/
import { Context } from './context';

/**
* A custom react hook exposing the registry context for use.
*
* This exposes the `registry` value provided via the
* <a href="#RegistryProvider">Registry Provider</a> to a component implementing
* this hook.
*
* It acts similarly to the `useContext` react hook.
*
* Note: Generally speaking, `useRegistry` is a low level hook that in most cases
* won't be needed for implementation. Most interactions with the wp.data api
* can be performed via the `useSelect` hook, or the `withSelect` and
* `withDispatch` higher order components.
*
* @example
* ```js
* const {
* RegistryProvider,
* createRegistry,
* useRegistry,
* } = wp.data
*
* const registry = createRegistry( {} );
*
* const SomeChildUsingRegistry = ( props ) => {
* const registry = useRegistry( registry );
* // ...logic implementing the registry in other react hooks.
* };
*
*
* const ParentProvidingRegistry = ( props ) => {
* return <RegistryProvider value={ registry }>
* <SomeChildUsingRegistry { ...props } />
* </RegistryProvider>
* };
* ```
*
* @return {Function} A custom react hook exposing the registry context value.
*/
export default function useRegistry() {
return useContext( Context );
}
Loading

0 comments on commit ce78cd8

Please sign in to comment.