Skip to content

Instantly share code, notes, and snippets.

@acousineau
Last active September 27, 2017 13:47
Show Gist options
  • Save acousineau/7f5a68f8d88903bf9228ec04574cc1e7 to your computer and use it in GitHub Desktop.
Save acousineau/7f5a68f8d88903bf9228ec04574cc1e7 to your computer and use it in GitHub Desktop.
Redux Selector Pattern Primer and Flow
// MyComponent.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchTheThings } from 'actions';
import { selectAsyncProp } from 'index-reducer';
class MyComponent extends Component {
componentDidMount() {
this.props.fetchTheThings();
}
render() {
return (
<div>
{ this.props.asyncProp && <span>{this.props.asyncProp}</span> }
</div>
);
}
};
const mapStateToProps = (state) => {
return {
asyncProp: selectAsyncProp(state),
};
};
const mapDispatchToProps = {
fetchTheThings,
};
export default connect(mapStateToProps, mapDispatchToProps)(MyComponent);
// actions.js
export const GET_THINGS = 'GET_THINGS';
export const fetchTheThings = () => dispatch => {
return fetch('endpointtosomewhere', { configstuffhere })
.then(res => res.json())
.then(data => {
dispatch({ type: GET_THINGS, data });
});
};
// reducer.js
import { GET_THINGS } from 'actions';
const defaultState = {
asyncProp: null,
};
export default (state = defaultState, action) => {
switch (action.type) {
case GET_THINGS:
return Object.assign({}, state, {
asyncProp: action.data
});
default:
return state;
}
};
export const getThingsAsyncProp = (state) => state.asyncProp;
// index-reducer.js
import { combineReducers } from 'redux';
import things, * as thingsSelectors from 'reducer';
export default combineReducers({
things,
});
export const selectAsyncProp = (state) => thingsSelectors.getThingsAsyncProp(state.things)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment