Created
December 25, 2016 08:13
-
-
Save guangningyu/fabf2e19aa0ae30b938575ea269cd65e to your computer and use it in GitHub Desktop.
An example of using POST method in a Saga.
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
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