docshelp wanted
Description
Hello,
The below example is a quick whip-up, but if you have any suggestions for improvement please let me know. In my case, and I'm guessing in many others', it's common to send one 'entity' to the backend in a request (like an object's ID), so I made this nice little RSAA action creator to abstract away that functionality. The 'apiRequestObject' can be any of the other valid RSAA action properties besides 'body' and 'types'. I then use Javascript's convenient bind() method to make more specific action creators.
So what does everyone think about incorporating an action creator factory for RSAAs?
/**
* Function for creating an RSAA action that concerns a certain entity. A lot of requests to the
* backend have just one entity sent in the POST body of the request, so
* this function abstracts away the entity and consolidates code.
* Use the Javascript bind() function to make action creators for requests that take a certain entity.
* @param entityName A string representing the name of the entity, to be used as the key in action payloads.
* @param apiRequestObject Other RSAA data for the request besides 'body' and 'types'
* @param fetchAction The name of the action to be dispatched for a waiting request.
* @param successAction The name of the action to be dispatched for a successful request.
* @param failureAction The name of the action to be dispatched for a failed request.
* @param entity The entity object to be passed in the POST body of the request.
* @returns {{}} The RSAA action constructed with the function parameters.
*/
export const entityRsaaActionCreator = (entityName,
apiRequestObject,
fetchAction,
successAction,
failureAction,
entity) => ({
[RSAA]: {
...apiRequestObject,
body: JSON.stringify({[entityName]: entity}),
types: [
{
type: fetchAction,
payload: (action, state) => ({[entityName]: entity})
},
{
type: successAction,
payload: (action, state, response) => {
if (response) {
return response.json().then(({data}) => ({[entityName]: entity, data}))
}
else {
return ({[entityName]: entity}); // if there's no response just return the entity
}
}
},
{
type: failureAction,
payload: (action, state, response) => ({[entityName]: entity})
}
]
}});