Last active
May 4, 2017 00:24
-
-
Save aduth/b36ac70f0d3cd3f61faa0b2b81b98a2a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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