Skip to content

Instantly share code, notes, and snippets.

@joeporpeglia
Created September 22, 2017 15:31
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save joeporpeglia/4d9197d90eb1b1673f42916e15507b81 to your computer and use it in GitHub Desktop.
Save joeporpeglia/4d9197d90eb1b1673f42916e15507b81 to your computer and use it in GitHub Desktop.
Redux as a Render Prop
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>
)}
/>
)
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,
});
}
}
@asfktz
Copy link

asfktz commented Nov 21, 2017

Nice !

@corlaez
Copy link

corlaez commented Jan 13, 2018

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

@corlaez
Copy link

corlaez commented Jan 13, 2018

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