index.js
4 years ago
useAuthors.js
3 years ago
useDebounceState.js
4 years ago
useDeviceType.js
3 years ago
useInnerBlocksCount.js
4 years ago
useRecordsReducer.js
3 years ago
useTaxonomies.js
4 years ago
useTaxonomyRecords.js
3 years ago
useAuthors.js
77 lines
| 1 | import { useSelect } from '@wordpress/data'; |
| 2 | import { store as coreStore } from '@wordpress/core-data'; |
| 3 | import useRecordsReducer from './useRecordsReducer'; |
| 4 | import { useEffect } from '@wordpress/element'; |
| 5 | import { isUndefined } from 'lodash'; |
| 6 | |
| 7 | /** |
| 8 | * Returns list of authors. |
| 9 | * |
| 10 | * @param {Object} query The query params. |
| 11 | * @return {{isResolving: boolean, records: Object}} The result set. |
| 12 | */ |
| 13 | export default function useAuthors( query = {} ) { |
| 14 | return useSelect( ( select ) => { |
| 15 | const { |
| 16 | getEntityRecords, |
| 17 | isResolving, |
| 18 | } = select( coreStore ); |
| 19 | |
| 20 | const queryParams = Object.assign( { |
| 21 | per_page: -1, |
| 22 | who: 'authors', |
| 23 | }, query ); |
| 24 | |
| 25 | // We have to check for undefined "include" here and delete it |
| 26 | // because somehow core does not return results if hasOwnProperty( 'include' ) returns true |
| 27 | if ( queryParams.hasOwnProperty( 'include' ) && isUndefined( queryParams.include ) ) { |
| 28 | delete queryParams.include; |
| 29 | } |
| 30 | |
| 31 | const entityParams = [ 'root', 'user', queryParams ]; |
| 32 | |
| 33 | return { |
| 34 | records: getEntityRecords( ...entityParams ) || [], |
| 35 | isResolving: isResolving( 'getEntityRecords', entityParams ), |
| 36 | }; |
| 37 | }, [ JSON.stringify( query ) ] ); |
| 38 | } |
| 39 | |
| 40 | /** |
| 41 | * Return author records persisting previous calls. |
| 42 | * |
| 43 | * @param {Object} queryParams The query params. |
| 44 | * @return {{isLoading: boolean, records: Object}} The result set. |
| 45 | */ |
| 46 | export function usePersistentAuthors( queryParams = {} ) { |
| 47 | const { |
| 48 | records, |
| 49 | setRecords, |
| 50 | query, |
| 51 | setQuery, |
| 52 | isLoading, |
| 53 | setIsLoading, |
| 54 | } = useRecordsReducer( { query: queryParams } ); |
| 55 | |
| 56 | useEffect( () => { |
| 57 | setQuery( queryParams ); |
| 58 | setIsLoading( true ); |
| 59 | }, [ JSON.stringify( queryParams ) ] ); |
| 60 | |
| 61 | const { records: authors, isResolving } = useAuthors( query ); |
| 62 | |
| 63 | useEffect( () => { |
| 64 | setIsLoading( isResolving ); |
| 65 | }, [ isResolving ] ); |
| 66 | |
| 67 | useEffect( () => { |
| 68 | setRecords( authors ); |
| 69 | setIsLoading( false ); |
| 70 | }, [ JSON.stringify( authors ) ] ); |
| 71 | |
| 72 | return { |
| 73 | records, |
| 74 | isLoading, |
| 75 | }; |
| 76 | } |
| 77 |