-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathindex.js
39 lines (35 loc) · 1.3 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
/**
* External dependencies
*/
// eslint-disable-next-line import/no-extraneous-dependencies
import isObject from 'lodash/isObject';
/**
* WordPress dependencies
*/
import { useSelect, useDispatch } from '@wordpress/data';
/**
* Hook for retrieving data from the WordPress REST API.
*
* @param {string} entity The entity to retrieve. ie. postType
* @param {string} kind The entity kind to retrieve. ie. posts
* @param {object | number} [query] Optional. Query to pass to the geEntityRecords request. Defaults to an empty object. If a number is passed, it is used as the ID of the entity to retrieve via getEntityRecord.
* @returns {Array} The data returned from the request.
*/
export const useRequestData = (entity, kind, query = {}) => {
const functionToCall = isObject(query) ? 'getEntityRecords' : 'getEntityRecord';
const { invalidateResolution } = useDispatch('core/data');
const { data, isLoading } = useSelect((select) => {
return {
data: select('core')[functionToCall](entity, kind, query),
isLoading: select('core/data').isResolving('core', functionToCall, [
entity,
kind,
query,
]),
};
});
const invalidateResolver = () => {
invalidateResolution('core', functionToCall, [entity, kind, query]);
};
return [data, isLoading, invalidateResolver];
};