/
index.js
62 lines (57 loc) · 1.61 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/**
* External dependencies
*
* @ignore
*/
import { selectOptions } from '@mypreview/unicorn-js-utils';
import useDeepCompareEffect from 'use-deep-compare-effect';
/**
* WordPress dependencies
*
* @ignore
*/
import { useState } from '@wordpress/element';
/**
* Internal dependencies
*
* @ignore
*/
import { useToast, useToggle } from '../';
import { apiClient } from '../utils';
/**
* Retrieve a list of product posts and refresh
* the list when any direct arguments change.
*
* @function
* @since 1.0.0
* @name useGetProducts
* @param {Object} args Arguments to be passed to the apiFetch method.
* @param {string} clientId The block’s client id.
* @return {Object} List of posts retrieved from the API along with a list of options to select from.
* @example
*
* const { productsOptions, productsQuery } = useGetProducts( { order: 'asc' }, clientId );
*/
export default ( args = {}, clientId ) => {
const [ options, setOptions ] = useState( [] );
const [ query, setQuery ] = useState( '' );
const [ loading, setLoading ] = useToggle();
const toast = useToast();
useDeepCompareEffect( () => {
setLoading();
apiClient
.get( '/wc/v3/products', { per_page: -1, status: 'publish', ...args } )
.then( ( data ) => {
setOptions( selectOptions( data, { id: 'value', name: 'label' }, [] ) );
setQuery( data );
} )
.catch( ( { statusText } ) => {
setQuery( [] );
toast( statusText );
} )
.then( () => {
setLoading();
} );
}, [ args, clientId ] );
return { isLoading: loading, productsOptions: options, productsQuery: query };
};