Skip to content

Instantly share code, notes, and snippets.

@guangningyu
Created December 25, 2016 08:13
Show Gist options
  • Save guangningyu/fabf2e19aa0ae30b938575ea269cd65e to your computer and use it in GitHub Desktop.
Save guangningyu/fabf2e19aa0ae30b938575ea269cd65e to your computer and use it in GitHub Desktop.
An example of using POST method in a Saga.
function statusHelper(response) {
if (response.status >= 200 && response.status < 300) {
return Promise.resolve(response);
}
return Promise.reject(new Error(response.statusText));
}
/* Function: handle the async api call
* Params:
* url: api url
* method: GET/POST...
* body: an javascript object, for POST method only
* Return:
* a Promise, which should be passed to a saga yield call function
* if server return success, resolve { res: ...returned result }
* if server return failure, resolve { err: ...error message }
*/
function fetchUrl(url, body) {
// url is only the last part of the full path
return fetch(`/api${url}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
body: JSON.stringify(body),
})
.then(statusHelper)
.then(response => response.json())
.then(res => ({ res }))
.catch(err => ({ err }));
}
/* Function: an example of using post method in saga
*/
function* userRequestsModuleCodeSaga(action) {
const moduleName = action.payload.moduleFqn;
const { res, err } = yield fetchUrl('/module/module_code', { moduleName });
yield put(moduleActions.serverReturnedCurrentModuleCodeEvt({ res, err }));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment