index.js
1 year ago
useAuthors.js
3 years ago
useBlockStyles.js
1 year ago
useDebounceState.js
4 years ago
useDeviceAttributes.js
2 years ago
useDeviceType.js
1 year ago
useInnerBlocksCount.js
4 years ago
useQueryReducer.js
1 year ago
useRecordsReducer.js
3 years ago
useSelectedBlockElements.js
2 years ago
useStyleIndicator.js
2 years ago
useTaxonomies.js
1 year ago
useTaxonomyRecords.js
3 years ago
useRecordsReducer.js
58 lines
| 1 | import { useReducer } from '@wordpress/element'; |
| 2 | import { unionBy, orderBy } from 'lodash'; |
| 3 | |
| 4 | const defaultState = { |
| 5 | query: {}, |
| 6 | records: [], |
| 7 | isLoading: false, |
| 8 | }; |
| 9 | |
| 10 | function init( initialState ) { |
| 11 | return Object.assign( {}, defaultState, initialState ); |
| 12 | } |
| 13 | |
| 14 | function recordsReducer( state, action ) { |
| 15 | const newState = { ...state }; |
| 16 | |
| 17 | switch ( action.type ) { |
| 18 | case 'SET_RECORDS': |
| 19 | return Object.assign( {}, newState, { |
| 20 | records: orderBy( |
| 21 | unionBy( newState.records, action.payload, 'id' ), |
| 22 | ( post ) => ( post.date ), |
| 23 | [ 'desc' ] |
| 24 | ), |
| 25 | } ); |
| 26 | |
| 27 | case 'SET_QUERY': |
| 28 | return Object.assign( {}, newState, { |
| 29 | query: Object.assign( {}, newState.query, action.payload ), |
| 30 | } ); |
| 31 | |
| 32 | case 'SET_IS_LOADING': |
| 33 | return Object.assign( {}, newState, { |
| 34 | isLoading: action.payload, |
| 35 | } ); |
| 36 | |
| 37 | case 'RESET': |
| 38 | return Object.assign( {}, newState, { records: [] } ); |
| 39 | |
| 40 | default: |
| 41 | return newState; |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | export default function useRecordsReducer( initialState = defaultState ) { |
| 46 | const [ state, dispatch ] = useReducer( recordsReducer, initialState, init ); |
| 47 | |
| 48 | return { |
| 49 | records: state.records, |
| 50 | setRecords: ( payload = [] ) => ( dispatch( { type: 'SET_RECORDS', payload } ) ), |
| 51 | query: state.query, |
| 52 | setQuery: ( payload = {} ) => ( dispatch( { type: 'SET_QUERY', payload } ) ), |
| 53 | isLoading: state.isLoading, |
| 54 | setIsLoading: ( payload = false ) => ( dispatch( { type: 'SET_IS_LOADING', payload } ) ), |
| 55 | reset: () => ( dispatch( { type: 'RESET' } ) ), |
| 56 | }; |
| 57 | } |
| 58 |