Created
September 22, 2017 15:31
-
-
Save joeporpeglia/4d9197d90eb1b1673f42916e15507b81 to your computer and use it in GitHub Desktop.
Redux as a Render Prop
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
import StoreProvider from './StoreProvider'; | |
const increment = { type: '@counter/increment' }; | |
const decrement = { type: '@counter/decrement' }; | |
const initialState = { count: 0 }; | |
const reducer = (state = initialState, action) => { | |
switch (action.type) { | |
case increment.type: | |
return { | |
count: state.count + 1, | |
}; | |
case decrement.type: | |
return { | |
cound: state.count - 1, | |
}; | |
} | |
return state; | |
} | |
export default () => ( | |
<StoreProvider | |
reducer={reducer} | |
render={({ state, dispatch }) => ( | |
<div> | |
<h1>Count: {state.count}</h1> | |
<button onClick={() => dispatch(increment)}>Increment</button> | |
<button onClick={() => dispatch(decrement)}>Decrement</button> | |
</div> | |
)} | |
/> | |
) |
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
import React from 'react'; | |
export default class StoreProvider extends React.Component { | |
constructor(props) { | |
super(props); | |
this.dispatch = this.createDispatch(props.reducer); | |
this.state = props.reducer(this.state, { type: '@store/init' }); | |
} | |
createDispatch(reducer) { | |
return (action) => { | |
const state = reducer(this.state, action); | |
this.setState(() => state); | |
return state; | |
}; | |
} | |
componentWillReceiveProps({ reducer }) { | |
if (reducer !== this.props.reducer) { | |
this.dispatch = this.createDispatch(reducer); | |
} | |
} | |
render() { | |
return this.props.render({ | |
dispatch: this.dispatch, | |
state: this.state, | |
}); | |
} | |
} |
It would be nice to have the connect version as well, without it react redux is incomplete.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I am not sure if this can break something or pure convention but a dispatcher is supposed to return the action it took as param instead of state. StoreProvider.js line 14