useQueryReducer.js
30 lines
| 1 | import { useReducer } from '@wordpress/element'; |
| 2 | |
| 3 | const ADD_QUERY_PARAMETER = 'add_query_parameter'; |
| 4 | const REMOVE_QUERY_PARAMETER = 'remove_query_parameter'; |
| 5 | |
| 6 | const queryReducer = function( queryState, action ) { |
| 7 | switch ( action.type ) { |
| 8 | case ADD_QUERY_PARAMETER: |
| 9 | return Object.assign( {}, queryState, action.payload ); |
| 10 | |
| 11 | case REMOVE_QUERY_PARAMETER: |
| 12 | const { [ action.payload ]: removedKey, ...newQueryState } = queryState; // eslint-disable-line no-unused-vars |
| 13 | return newQueryState; |
| 14 | |
| 15 | default: |
| 16 | throw new Error( `queryReducer does not support action type "${ action.type }".` ); |
| 17 | } |
| 18 | }; |
| 19 | |
| 20 | export default ( initialQueryState = {} ) => { |
| 21 | const [ state, dispatch ] = useReducer( queryReducer, initialQueryState ); |
| 22 | |
| 23 | return { |
| 24 | queryState: state, |
| 25 | setParameter: ( key, value ) => ( dispatch( { type: ADD_QUERY_PARAMETER, payload: { [ key ]: value } } ) ), |
| 26 | insertParameters: ( payload ) => ( dispatch( { type: ADD_QUERY_PARAMETER, payload } ) ), |
| 27 | removeParameter: ( payload ) => ( dispatch( { type: REMOVE_QUERY_PARAMETER, payload } ) ), |
| 28 | }; |
| 29 | }; |
| 30 |