action-creatorintermediatefunction fetchUser(id) {
return function(dispatch) {
dispatch({ type: 'FETCH_USER_REQUEST' })
return fetch('/users/' + id)
.then(r => r.json())
.then(user => dispatch({ type: 'FETCH_USER_SUCCESS', payload: user }))
.catch(err => dispatch({ type: 'FETCH_USER_FAILURE', error: err.message }))
}
}The request/success/failure pattern gives the UI clear signals to show loading spinners and error messages.
A typical thunk action creator dispatches three actions for async operations:
REQUEST action immediately (shows a loading state)SUCCESS action when the data arrivesFAILURE action if something goes wrongfunction fetchUser(id) {
return function(dispatch) {
dispatch({ type: 'FETCH_USER_REQUEST' })
return fetch('/users/' + id)
.then(r => r.json())
.then(user => dispatch({ type: 'FETCH_USER_SUCCESS', payload: user }))
}
}
Challenge: Implement fetchUser(id) that dispatches 'FETCH_USER_REQUEST' immediately and returns a Promise that resolves with a success dispatch.