Skip to content

Instantly share code, notes, and snippets.

@l0gicgate
Last active November 23, 2017 22:19
Show Gist options
  • Save l0gicgate/d6a542620d226a9b236390ca8d6c293c to your computer and use it in GitHub Desktop.
Save l0gicgate/d6a542620d226a9b236390ca8d6c293c to your computer and use it in GitHub Desktop.
export const FETCH_DATA = 'FETCH_DATA';
export const FETCH_DATA_SUCCESS = 'FETCH_DATA_SUCCESS';
export const FETCH_DATA_ERROR = 'FETCH_DATA_ERROR';
export function fetchData() {
return {
type: FETCH_DATA,
};
}
export function fetchDataSuccess(data) {
return {
type: FETCH_DATA_SUCCESS,
data,
};
}
export function fetchDataError() {
return {
type: FETCH_DATA_ERROR,
};
}
import React from 'react';
import ReactDOM from 'react-dom';
import Hydrator from './Hydrator';
import DataComponent from './DataComponent';
const App = () => <Hydrator><DataComponent /></Hydrator>;
ReactDOM.render(<App />, 'app');
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
const DataComponent = ({ data }) => <div>{data.name}</div>;
DataComponent.propTypes = {
data: PropTypes.object.isRequired,
};
function mapStateToProps({ store: { data } }) {
return { data };
}
export default connect(mapStateToProps)(DataComponent);
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { fetchData } from './actions';
class Hydrator extends React.Component {
static propTypes = {
children: PropTypes.oneOf([
PropTypes.array,
PropTypes.object,
]).isRequired,
fetchData: PropTypes.func.isRequired,
store: PropTypes.object.isRequired,
};
componentWillMount() {
const { loading, data, error } = this.props.store;
if (!loading && !data && !error) {
this.props.fetchData();
}
}
render() {
const { children, store } = this.props;
return store.loading || !store.data
? 'Loading...'
: this.props.children;
}
}
function mapStateToProps({ store }) {
return { store };
}
function mapDispatchToProps(dispatch) {
return {
fetchData: () => dispatch(fetchData()),
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Hydrator);
import { FETCH_DATA, FETCH_DATA_SUCCESS, FETCH_DATA_ERROR } from './actions';
const initialState = {
loading: false,
data: null,
error: false,
};
export default function reducer(state = initialState, action) {
switch (action.type) {
case FETCH_DATA:
return Object.assign({}, state, {
loading: true,
error: false,
});
case FETCH_DATA_SUCCESS:
return Object.assign({}, state, {
loading: false,
data: action.data,
});
case FETCH_DATA_ERROR;
return Object.assign({}, state, {
loading: false,
error: true,
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment