I wonder if a generic request saga makes any sense?
It would take a REQUEST
action that contains all the infos like headers, url, data and would merge it with its own headers and base URL.
It would then fetch
the request and then put(REQUEST_SUCCEEDED, json)
with the json payload in the store.
const request = yield take(REQUEST)
const { url, data, headers } = request
try {
if (request.startAction) {
yield put(request.startAction)
}
const json = yield call(api.fetch, url, data, headers)
yield put({...request.successAction, json})
} catch (error) {
yield put({...request.errorAction, error})
}
As I understand it this would only allow one request at a time, so instead of calling the API fetch function a fork
would be better?
The saga could also take care of managing the API access_token
once it encounters it in the response headers and save it for all subsequent requests.
function getAction(action) {
if (action) {
if (typeof action === "string") {
return { type: action }
} else {
return action
}
}
}
export function request(url, data, headers, actions) {
let result = {
type: REQUEST,
url, data, headers
}
actions[0] && result.startAction = getAction(actions[0])
actions[1] && result.successAction = getAction(actions[1])
actions[2] && result.errorAction = getAction(actions[2])
return result
}
There are several questions asked here.
Yes. Generic request saga makes sense to me. A place to provide standard for all requests makes sense.
Fork is most definitely needed. Or rather use takeEvery
helper. This is to prevent missing some request while the saga is processing fetch
. A default timeout may be needed to be implemented as well using race
.
The actions
parameter in request
function would be better to be object than array with keys of startAction
. An alternative is to give request a name. And make generic suffix for each action (eg. GETSTH_START, GETSTH_SUCCESS, GETSTH_ERROR)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With