PluginProbe ʕ •ᴥ•ʔ
GenerateBlocks / 1.8.2
GenerateBlocks v1.8.2
trunk 1.0 1.0.1 1.0.2 1.1.0 1.1.1 1.1.2 1.2.0 1.3.0 1.3.1 1.3.2 1.3.3 1.3.4 1.3.5 1.4.0 1.4.1 1.4.2 1.4.3 1.4.4 1.5.0 1.5.1 1.5.2 1.5.3 1.5.4 1.6.0 1.7.0 1.7.1 1.7.2 1.7.3 1.8.0 1.8.1 1.8.2 1.8.3 1.9.0 1.9.1 2.0.0 2.0.1 2.0.2 2.1.0 2.1.1 2.1.2 2.2.0 2.2.1 2.3.0
generateblocks / src / hooks / useTaxonomyRecords.js
generateblocks / src / hooks Last commit date
index.js 4 years ago useAuthors.js 3 years ago useDebounceState.js 4 years ago useDeviceAttributes.js 2 years ago useDeviceType.js 2 years ago useInnerBlocksCount.js 4 years ago useRecordsReducer.js 3 years ago useTaxonomies.js 4 years ago useTaxonomyRecords.js 3 years ago
useTaxonomyRecords.js
79 lines
1 import { isUndefined } from 'lodash';
2 import { useSelect } from '@wordpress/data';
3 import { store as coreStore } from '@wordpress/core-data';
4 import { useEffect } from '@wordpress/element';
5 import useRecordsReducer from './useRecordsReducer';
6
7 /**
8 * Return records for a given taxonomy.
9 *
10 * @param {string} taxonomy The taxonomy.
11 * @param {Object} query The query params.
12 * @return {{isResolving: boolean, records: Object}} The result set.
13 */
14 export default function useTaxonomyRecords( taxonomy, query = {} ) {
15 return useSelect( ( select ) => {
16 const {
17 getEntityRecords,
18 isResolving,
19 } = select( coreStore );
20
21 const queryParams = Object.assign( { per_page: -1 }, query );
22
23 // We have to check for undefined "include" here and delete it
24 // because somehow core does not return results if hasOwnProperty( 'include' ) returns true
25 if ( queryParams.hasOwnProperty( 'include' ) && isUndefined( queryParams.include ) ) {
26 delete queryParams.include;
27 }
28
29 const entityParams = [ 'taxonomy', taxonomy, queryParams ];
30
31 return {
32 records: getEntityRecords( ...entityParams ) || [],
33 isResolving: isResolving( 'getEntityRecords', entityParams ),
34 };
35 }, [ taxonomy, JSON.stringify( query ) ] );
36 }
37
38 /**
39 * Return records for a given taxonomy but persisting previous calls.
40 *
41 * @param {string} taxonomy The taxonomy.
42 * @param {Object} params The query params to retrieve the records.
43 * @return {{records: Object, isLoading: boolean}} The result set.
44 */
45 export function usePersistentTaxonomyRecords( taxonomy, params = {} ) {
46 const {
47 records,
48 setRecords,
49 query,
50 setQuery,
51 isLoading,
52 setIsLoading,
53 reset,
54 } = useRecordsReducer( { query: params } );
55
56 useEffect( () => {
57 reset();
58 }, [ taxonomy ] );
59
60 useEffect( () => {
61 setQuery( params );
62 }, [ JSON.stringify( params ) ] );
63
64 const { records: data, isResolving } = useTaxonomyRecords( taxonomy, query );
65
66 useEffect( () => {
67 setIsLoading( isResolving );
68 }, [ isResolving ] );
69
70 useEffect( () => {
71 setRecords( data );
72 }, [ JSON.stringify( data ) ] );
73
74 return {
75 records,
76 isLoading,
77 };
78 }
79