index.js
84 lines
| 1 | /** |
| 2 | * WordPress dependencies |
| 3 | */ |
| 4 | import { createReduxStore, register } from '@wordpress/data'; |
| 5 | import apiFetch from '@wordpress/api-fetch'; |
| 6 | |
| 7 | /** |
| 8 | * Internal dependencies |
| 9 | */ |
| 10 | import { STORE_NAME, API_PATH } from './constants'; |
| 11 | |
| 12 | export const updateOptions = (options) => { |
| 13 | apiFetch({ |
| 14 | path: API_PATH, |
| 15 | method: 'POST', |
| 16 | data: options, |
| 17 | }); |
| 18 | }; |
| 19 | |
| 20 | const DEFAULT_STATE = { |
| 21 | options: {}, |
| 22 | }; |
| 23 | |
| 24 | /** |
| 25 | * Store definition for the block-editor namespace. |
| 26 | * |
| 27 | * @see https://github.com/WordPress/gutenberg/blob/HEAD/packages/data/README.md#createReduxStore |
| 28 | * |
| 29 | * @type {Object} |
| 30 | */ |
| 31 | const actions = { |
| 32 | setOptions(options) { |
| 33 | return { |
| 34 | type: 'SET_OPTIONS', |
| 35 | options, |
| 36 | }; |
| 37 | }, |
| 38 | |
| 39 | fetchFromAPI(path) { |
| 40 | return { |
| 41 | type: 'FETCH_FROM_API', |
| 42 | path, |
| 43 | }; |
| 44 | }, |
| 45 | }; |
| 46 | |
| 47 | const store = createReduxStore(STORE_NAME, { |
| 48 | reducer(state = DEFAULT_STATE, action) { |
| 49 | switch (action.type) { |
| 50 | case 'SET_OPTIONS': |
| 51 | return { |
| 52 | ...state, |
| 53 | options: action.options, |
| 54 | }; |
| 55 | } |
| 56 | |
| 57 | return state; |
| 58 | }, |
| 59 | |
| 60 | actions, |
| 61 | |
| 62 | selectors: { |
| 63 | getOptions(state) { |
| 64 | const { options } = state; |
| 65 | return options; |
| 66 | }, |
| 67 | }, |
| 68 | |
| 69 | controls: { |
| 70 | FETCH_FROM_API(action) { |
| 71 | return apiFetch({ path: action.path }); |
| 72 | }, |
| 73 | }, |
| 74 | |
| 75 | resolvers: { |
| 76 | *getOptions() { |
| 77 | const options = yield actions.fetchFromAPI(API_PATH); |
| 78 | return actions.setOptions(options); |
| 79 | }, |
| 80 | }, |
| 81 | }); |
| 82 | |
| 83 | register(store); |
| 84 |