Skip to content

Instantly share code, notes, and snippets.

@aduth
Created December 15, 2016 14:46
Show Gist options
  • Save aduth/96223853d4e9c9388942a5889c49be02 to your computer and use it in GitHub Desktop.
Save aduth/96223853d4e9c9388942a5889c49be02 to your computer and use it in GitHub Desktop.
redux effects middleware
// state/effects.js
/**
* Internal dependencies
*/
import post from './post/effects';
export default [
post
];
// state/index.js
/**
* External dependencies
*/
import { createStore, applyMiddleware } from 'redux';
import effectsMiddleware from 'effects-middleware';
/**
* Internal dependencies
*/
import reducer from './reducer';
import effects from './effects';
export default function configureStore() {
return createStore( reducer, null, applyMiddleware( effectsMiddleware( effects ) ) );
}
// state/posts/actions.js
export function requestPost( postId ) {
return {
type: 'POST_REQUEST',
postId
};
}
export function receivePost( post ) {
return {
type: 'POST_RECEIVE',
post
};
}
// state/posts/effects.js
/**
* Internal dependencies
*/
import { receivePost } from './actions';
export default {
POST_REQUEST: async ( action, store ) => {
const response = await fetch( `/posts/${ action.postId }` );
const post = await response.json();
store.dispatch( receivePost( post ) );
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment