PluginProbe ʕ •ᴥ•ʔ
GenerateBlocks / 2.1.1
GenerateBlocks v2.1.1
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 / useRecordsReducer.js
generateblocks / src / hooks Last commit date
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