Skip to content

Instantly share code, notes, and snippets.

@aduth
Last active May 4, 2017 00:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aduth/b36ac70f0d3cd3f61faa0b2b81b98a2a to your computer and use it in GitHub Desktop.
Save aduth/b36ac70f0d3cd3f61faa0b2b81b98a2a to your computer and use it in GitHub Desktop.
// Action creators
function savePost( post ) {
return {
type: 'SAVE_POST',
post
};
}
function receivePost( post ) {
return {
type: 'RECEIVE_POST',
post
};
}
// Side effects mapping
const effects = {
SAVE_POST: ( action ) => ( {
type: 'REQUEST',
url: '/wp-json/wp/v2/posts',
params: {
method: 'POST',
body: encodeURIComponent( post )
},
success: receivePost
} )
};
// Middlewares
const effectsMiddleware = ( store ) => ( next ) => ( action ) => {
if ( effects.hasOwnProperty( action.type ) {
store.dispatch( effects[ action.type ]( action ) );
}
return next( action );
};
const requestMiddleware = ( store ) => ( next ) => ( action ) => {
if ( 'REQUEST' === action.type ) {
window.fetch( action.url, action.params )
.then( ( response ) => response.json() )
.then( ( data ) => store.dispatch( action.success( data ) ) );
}
return next( action );
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment