Create a gist now

Instantly share code, notes, and snippets.

Embed
One update cycle on init / success / failure of a network request.
export const finishRegistration = ({ id, attributes }) => (dispatch) => {
dispatch({
type: 'FINISH_REGISTRATION',
payload: { id }
})
return finish({ id, attributes }).then(({
registration,
personalCampaign,
account
}) => {
dispatch(finishRegistrationSuccess({
registration,
personalCampaign,
account
}))
return {
registration,
personalCampaign,
account
}
})
}
const finishRegistrationSuccess = ({
registration,
personalCampaign,
account
}) => ({
type: 'FINISH_REGISTRATION_SUCCESS',
payload: {
registration,
personalCampaign,
account
}
})
const finishRegistrationFailure = ({
error,
registration,
personalCampaign,
account
}) => ({
type: 'FINISH_REGISTRATION_FAILURE',
error,
payload: {
registration,
personalCampaign,
account
}
})
const personalCampaignsReducer = (state = {}, { type, payload, error }) => {
switch (type) {
case 'FINISH_REGISTRATION_SUCCESS': {
const { personalCampaign } = payload
// ... etc
}
// ... etc
}
}
const accountsReducer = (state = {}, { type, payload, error }) => {
switch (type) {
case 'FINISH_REGISTRATION_SUCCESS': {
const { account } = payload
// ... etc
}
// ... etc
}
}
const fetchFoo = (id) => (
get(`http://url/foos/${id}`).then(({ data }) => (data))
)
const fetchBar = (id) => (
get(`http://url/bars/${id}`).then(({ data }) => (data))
)
const fetchFooBar = ({ fooId, barId }) => (
Promise.all([
fetchFoo(fooId),
fetchBar(barId)
]).then(([foo, bar]) => ({
foo,
bar
}))
)
const fetchRequiredData = (ids) => (dispatch) => {
dispatch({ type: 'FETCH_REQUIRED_DATA_REQUEST', payload: ids })
return fetchFooBar(ids).then(payload => {
dispatch({ type: 'FETCH_REQUIRED_DATA_SUCCESS', payload })
return result
}).catch(error => {
dispatch({ type: 'FETCH_REQUIRED_DATA_FAILURE', error })
return Promise.reject(error)
})
}
const foosReducer = (state = {}, { type, payload, error }) => {
switch (type) {
case 'FETCH_REQUIRED_DATA': {
// update the specific foo in the store!
}
// ... etc
}
}
const barsReducer = (state = {}, { type, payload, error }) => {
switch (type) {
case 'FETCH_REQUIRED_DATA': {
// update the specific bar in the store!
}
// ... etc
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment