Skip to content

Instantly share code, notes, and snippets.

@fraserxu
Created January 5, 2017 00:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fraserxu/0f11a8c5c6e7a9e66361b16656e63d2a to your computer and use it in GitHub Desktop.
Save fraserxu/0f11a8c5c6e7a9e66361b16656e63d2a to your computer and use it in GitHub Desktop.
handle chained async actions in redux
const loadUserRequest = { type: 'loadUserRequest' }
const loadUserSuccess = (user) => ({ type: 'loadUserSuccess', payload: user })
const loadUserFailure = (err) => ({ type: 'loadUserFailure', err })
const loadPostsRequest = { type: 'loadPostsRequest' }
const loadPostsSuccess = (posts) => ({ type: 'loadPostsSuccess', payload: posts })
const loadPostsFailure = (err) => ({ type: 'loadPostsFailure', err })
const loadUser = () => {
return (dispatch) => {
dispatch(loadUserRequest)
API.loadUser().then((user) => {
return dispatch(loadUserSuccess(user))
}).catch((err) => {
return dispatch(loadUserFailure(err))
})
}
}
const loadPosts = (token) => {
return (dispatch) => {
dispatch(loadPostsReqeust)
API.loadPosts(token).then((posts) => {
return dispatch(loadPostsSuccess(posts))
}).catch((err) => {
return dispatch(loadPostsFailure(err))
})
}
}
import React from 'react'
export default class AppComponent extends React.Component {
componentDidMount () {
const { loadUser, loadPosts } = this.props
loadUser().then((action) => {
/** ATTENTION HERE
* the load posts actions only happends when load user success
* is this the right place to trigger
*/
if (action && action.type === 'loadUserSuccess') {
const user = action.payload
loadPosts(user.token)
/** ATTENTION HERE
* maybe I will also have `loadPostComment` and more and more. Is this the right place to do them?
*/
}
})
}
render () {
const { user, posts } = this.props
return (<section>
<span>{user.name}</span>
<ul>
{posts.map((post) => {
return <li>{post.title}</li>
})}
<ul>
</section>)
}
}
import App from './appComponent'
import { connect } from 'react-redux'
import {
loadUser,
loadPosts
} from './appActions'
const mapStateToProps = (state) => {
const { posts, user } = state
return {
user,
posts
}
}
const mapDispatchToProps = (dispatch) => {
return {
loadUser: () => dispatch(loadUser()),
loadPosts: (token) => dispatch(loadPosts(token))
}
}
export default const AppContainer = connect(
mapStateToProps,
mapDispatchToProps
)(App)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment