I have this working in my plugin and all is well with the world:
edit: withAPIData( props => {
return {
roles: '/matt-watson/secure-blocks/v1/user-roles/'
};
} )( props => {
....
However guidance here suggests that this will no longer be supported going forward: https://github.com/WordPress/gutenberg/issues/7390#issuecomment-398667802
So I have managed to work that into the solution:
const DEFAULT_STATE = {
userRoles: {},
};
const actions = {
setUserRoles( userRoles ) {
return {
type: 'SET_USER_ROLES',
userRoles,
};
},
fetchFromAPI( path ) {
return {
type: 'FETCH_FROM_API',
path,
};
},
};
registerStore( 'matt-watson/secure-block', {
reducer( state = DEFAULT_STATE, action ) {
switch ( action.type ) {
case 'SET_USER_ROLES':
return {
...state,
userRoles: action.userRoles,
};
}
return state;
},
actions,
selectors: {
getUserRoles( state ) {
const { userRoles } = state;
return userRoles;
},
},
controls: {
FETCH_FROM_API( action ) {
return apiFetch( { path: action.path } );
},
},
resolvers: {
* getUserRoles( state ) {
const path = '/matt-watson/secure-blocks/v1/user-roles/';
const userRoles = yield actions.fetchFromAPI( path );
return actions.setUserRoles( userRoles );
},
}
,
} );
....
edit: withSelect( ( select ) => {
return {
roles: select('matt-watson/secure-block').getUserRoles(),
};
} )( props => {
....
Now the issue is that the 'controls' section never fires. In the documentation it says that this is an opt-in component, and I need to enable it via the use
command: https://github.com/WordPress/gutenberg/tree/master/packages/data#controls
When I try this, use
is undefined.
So my question is this. As withAPIData
did everything I needed in a very quick and easy way, is there an alternative 'drop-in' bit of code I can use, or do I need to progress with the store that I am registering? If so, what am I doing wrong?
Any help appreciated. Thank you.
...
is also valid javascript, as the object spread operatoruse
...
I'll have to come up with another way to add snippets. I'll have another look intouse
. If I fix this I'll write a glorious blog post!