Created
February 14, 2019 03:03
-
-
Save Necmttn/ecaddad992dbe98316cdbddc6e131a55 to your computer and use it in GitHub Desktop.
Better way of making Redux Ajax actions.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const REQUEST = 'REQUEST' | |
const SUCCESS = 'SUCCESS' | |
const FAILURE = 'FAILURE' | |
function action(type, payload = {}) { | |
return {type, ...payload} | |
} | |
const listJDs = { | |
request: () => action(ActionTypes.LIST_JDS[REQUEST]), | |
success: (jobs, mostUrgent) => action(ActionTypes.LIST_JDS[SUCCESS], {jobs, mostUrgent}), | |
failure: (error) => action(ActionTypes.LIST_JDS[FAILURE], {error}), | |
} | |
export function getListJDs() { | |
return function (dispatch, getState) { | |
dispatch(listJDs.request()); | |
const { auth: { token } } = getState(); | |
return API.listJDs(token) | |
.then((response) => { | |
const jobs = getField(response, 'data.data') | |
let mostUrgent = null | |
jobs.forEach((job) => { | |
if (job.applicants.length > 0) { | |
if (mostUrgent) { | |
if (job.applicants[0].dateReceived < mostUrgent.applicants[0].dateReceived) { | |
mostUrgent = job; | |
} | |
} else { | |
mostUrgent = job; | |
} | |
} | |
}) | |
dispatch(listJDs.success(jobs, mostUrgent)); | |
}) | |
.catch((err) => { | |
dispatch(listJDs.failure(err)); | |
}); | |
}; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment