Skip to content

Instantly share code, notes, and snippets.

@joeporpeglia
Last active February 26, 2019 18:45
Show Gist options
  • Save joeporpeglia/44d0f2fc5afc49f0a2ee00d718a08241 to your computer and use it in GitHub Desktop.
Save joeporpeglia/44d0f2fc5afc49f0a2ee00d718a08241 to your computer and use it in GitHub Desktop.
React Redux with the new React Context API. I didn't test this at all...
import React from 'react';
import Counter from './counter';
const mapProps = ({ state, dispatch }) => ({
count: state,
increment: () => dispatch({
type: 'increment',
}),
decrement: () => dispatch({
type: 'decrement',
}),
});
const Container = () => (
<Counter.Connect mapStateToProps={mapProps}>
{({ count, increment, decrement }) => (
<form>
<button onClick={increment}>increment</button>
<button onClick={decrement}>decrement</button>
<span>Count: {count}</span>
</form>
)}
</Counter.Connect>
);
export default () => (
<Counter>
<Container />
</Counter>
);
import React from 'react';
import createReducerComponent from './create-reducer-component';
export default createReducerComponent((state = 0, action) => {
switch (action.type) {
case 'increment':
return state + 1;
case 'decrement':
return state - 1;
}
return state;
});
import React from 'react';
export default (reducer, externalState = null) => {
const initialState = reducer(externalState, { type: '__INIT__' });
if (initialState !== externalState) {
throw new Error('Reducer should be pure');
}
const context = React.createContext({
state: initialState,
actions,
});
return class ReducerComponent extends React.Component {
static Connect = ({ mapStateToProps, children }) => (
<context.Consumer>
{(store) => children(mapStateToProps(store))}
</context.Consumer>
);
state = initialState;
dispatch = (action) => {
this.setState((prevState) => {
return reducer(prevState, action);
});
};
createApi() {
return {
state: this.state,
dispatch: this.dispatch,
};
}
render() {
return (
<context.Provider value={this.createApi()}>
{this.props.children}
</context.Provider>
)
}
}
};
@marcomarchiaro
Copy link

At line 12 we have actions that is not recognized.
Where is initializatied?
Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment