Skip to content

Instantly share code, notes, and snippets.

@codebutler
Created August 30, 2018 22:07
Show Gist options
  • Save codebutler/6668590ffd6a14c6b712447277dfa24e to your computer and use it in GitHub Desktop.
Save codebutler/6668590ffd6a14c6b712447277dfa24e to your computer and use it in GitHub Desktop.
// actions/polls.js
export const FETCH_SUCCESS = `POLLS_FETCH_SUCCESS`;
export const FETCH_FAILURE = `POLLS_FETCH_FAILURE`;
function fetch() {
return (dispatch) => {
// Set API URL and request options, then...
fetch(url, options)
.then((response) => response.json())
.then((pollsAndVotes) => {
dispatch(fetchSuccess(pollsAndVotes));
})
.catch((error) => dispatch(fetchFailure()));
}
}
function fetchSuccess(pollsAndVotes) {
return {
type: FETCH_LIST_SUCCESS,
pollsAndVotes
}
}
function fetchFailure() {
// ...
}
// reducers/polls.js
import * as pollsActions from '../actions/polls';
export function polls(state = {}, action) {
switch(action.type) {
case pollsActions.FETCH_SUCCESS:
return action.pollsAndVotes.polls;
default:
return state;
}
}
// reducers/votes.js
import * as pollsActions from '../actions/polls';
export function votes(state = {}, action) {
switch(action.type) {
case pollsActions.FETCH_SUCCESS:
return action.pollsAndVotes.votes;
default:
return state;
}
}
// PollsContainer.js
import { fetch as fetchData } from './actions/polls';
// ...
const mapStateToProps = (state) => {
return {
polls: state.polls,
votes: state.votes
}
};
const mapDispatchToProps = (dispatch) => {
return {
loadData: () => dispatch(fetchData())
};
}
class PollsContainer extends React.Component {
componentDidMount() {
this.props.loadData();
}
getVotesForPoll(pollId) {
return this.state.votes[pollId];
}
// ...
render() {
// ...
return (
<div>
{this.state.polls.map((poll) => <Poll poll={poll} votes={getVotesForPoll(vote.id)} />)}
</div>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment