Forked from markerikson/redux-ajax-request-examples.js
Created
April 14, 2018 21:05
-
-
Save barbagrigia/948269adf2a7cdc5ba525772dd4662ad to your computer and use it in GitHub Desktop.
Redux AJAX request examples
This file contains hidden or 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
// Option 1: a thunk action creator using redux-thunk middleware | |
function myThunkActionCreator(someValue) { | |
return (dispatch, getState) => { | |
dispatch({type : "REQUEST_STARTED"}); | |
myAjaxLib.post("/someEndpoint", {data : someValue}) | |
.then( | |
// Use the (resolve, reject) form of .then() instead of .catch(), | |
// so that we don't accidentally dispatch REQUEST_FAILED on a reducer error | |
response => dispatch({type : "REQUEST_SUCCEEDED", payload : response}), | |
error => dispatch({type : "REQUEST_FAILED", error : error}) | |
). | |
}; | |
} | |
// Option 2: a generator function that listens for a "MAKE_AJAX_CALL" action, using redux-saga middleware | |
function* myNetworkRequestSaga() { | |
while(true) { | |
const action = yield take("MAKE_AJAX_CALL"); | |
const data = action.someValue; | |
yield put({type : "REQUEST_STARTED"); | |
try { | |
const response = yield call(myAjaxLib.post, "/someEndpoint", {data} | |
yield put({type : "REQUEST_SUCCEEDED", payload : response}); | |
} | |
catch(error) { | |
yield put({type : "REQUEST_FAILED", error}); | |
} | |
} | |
} | |
// Option 3: a function that dispatches a "MAKE_AJAX_CALL" action, with a custom network request middleware | |
function requestAjaxCallFromMiddleware(someValue) { | |
return { | |
type : "MAKE_AJAX_CALL", | |
payload : { | |
requestType : "POST", | |
endpoint : "/someEndpoint", | |
data : someValue | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment