redux-api-saga
REACT API calls made simple
Its an abstraction on top of redux-saga. Takes in a config and gives you a reducer saga and a common action.
Setup
// store.js;;;; const defaultOnSuccess = { console;};const defaultOnError = { ;};const config = path: 'http://localhost:3001/auth' method: 'POST' name: 'authToken' // API will be referred in action using this name mode: 'takeLatest' initialResult: null // this is the initial value, onSuccess: defaultOnSuccess onError: defaultOnError path: 'http://localhost:3001/puppyJpg/:imageId' method: 'GET' name: 'puppyJpg' mode: 'takeLatest' initialResult: 'https://upload.wikimedia.org/wikipedia/commons/9/9c/Indian_pariah_dog_puppy_%288334906336%29.jpg' ;// default set of headers. you can choose to override this in every action dispatch. const getReqHeaders = Authorization: `bearer `;const options = getReqHeadersDefault: getReqHeaders;const apiSaga = ; const reducer = apiSagareducer;const sagas = apiSagasagas;const action = apiSagaaction; { ;} // create middlewaresconst sagaMiddleware = ;const middleware = ;// create storeconst store = ;;// run saga middlewaresagaMiddleware;
Usage
// auth.jsx ; ... { thisprops;}
// puppy.jsx; ... Component state = {}; { thisprops; // resultant API path -> http://localhost:3001/puppyJpg/20345?resolution=HD } { return <div> <button onClick=thisgetPuppyImg> Test </button> <img src=thispropspuppyJpg /> </div> ; } const mapState = puppyJpg: statepuppyJpg; mapStatePuppyImg;
Cancel a request
Use onDispatch
hook to get the cancel function
example ->
Component cancelRequest = null { thisprops; // resultant API path -> http://localhost:3001/puppyJpg/20345?resolution=HD } { thiscancelRequest && this } // Now call cancelPuppyImgCall in case you want to give user an option to cancel the request
Reset state
thisprops