score:0
here is an approach to handle api request using redux-saga:
first create a request helper
import 'whatwg-fetch';
function parsejson(response) {
return response.json ? response.json() : response;
}
/**
* checks if a network request came back fine, and throws an error if
not
*
* @param {object} response a response from a network request
*
* @return {object|undefined} returns either the response, or throws an
* error
*/
function checkstatus(response, checktoken = true) {
if (response.status >= 200 && response.status < 300) {
return response;
}
return parsejson(response).then(responseformatted => {
const error = new error(response.statustext);
error.response = response;
error.response.payload = responseformatted;
throw error;
});
}
/**
* requests a url, returning a promise
*
* @param {string} url the url we want to request
* @param {object} [options] the options we want to pass to "fetch"
*
* @return {object} the response data
*/
export default function request(url, options = {}) {
// set headers
if (!options.headers) {
options.headers = object.assign({
'content-type': 'application/json',
}, options.headers, {});
}
// stringify body object
if (options && options.body) {
options.body = json.stringify(options.body);
}
return fetch(url, options)
.then(checkstatus)
.then(parsejson)
}
in your saga
import { call, fork, put, takelatest } from 'redux-saga/effects';
import request from 'utils/request';
import { submitsuccess, submiterror } from './actions'; // path
to your actions.
import { submit } from './constants'; // the event you're listening
export function* submitdata(action) {
try {
const response = yield call(request, 'your_url', { method: 'post', body: action.body });
yield put(submitsuccess(response));
} catch(err) {
yield put(submiterror(response.payload.message);
}
}
export function* defaultsaga() {
yield fork(takelatest, submit, submitdata);
}
export default defaultsaga;
reducer
const initialstate = fromjs({
submitsuccess: false,
submitreponse: '',
errormessage: '',
});
function fooreducer(state = initialstate, action) {
switch (action.type) {
case submit_success:
return state
.update('submitsuccess', () => true)
.update('submitresponse', () => action.response);
case submit_error:
return state.update('errormessage', () => action.errormessage);
//...
}
}
with this structure you should be able to catch your success and you error when you're making your request.
score:1
you shouldn't be defining the success
in your api request.
$.ajax will return a promise on its own:
const firstapirequest = () => (
$.ajax({
url: myurl,// ,
type:'post',
headers:{
"accept":"application/json",
"content-type":"application/json",
},
data:json.stringify(bodydata),
}));
also, why are you using jquery for making the api requests? i'd suggest using axios or fetch
Source: stackoverflow.com
Related Query
- redux saga ajax call - not working as expected
- React Redux is not working as expected with Next.js & NodeJS
- "Res.redirect" Not Working when making Ajax call from React to Node?
- AJAX call not working in React once I change state
- local storage with redux not working as expected
- React Redux onClick Call to Action Creator Not Working
- React Redux - useState Hook not working as expected
- Debounce not working as expected react context, api call
- redux useEffect and useDispatch not working (max call stack)?
- Trying to use Redux for toggling a modal but it is not working as expected
- Redux Saga call not taking localStorage tokens
- Redux saga yield call not waiting with firebase?
- JEST testing on redux is not working as expected
- Why Redux Saga yield call return a function, not data?
- Redux Saga does not work after any error. It totally stops working and need to refresh the page
- Code not working after redux function in axios call
- react-redux ssr async api call not working as expected
- Jest expect.any() not working as expected
- React router v4 not working with Redux
- Formik & yup form validation not working as expected with VirtualizedSelect
- Can I send an AJAX call in React and Redux without action creators and reducers?
- In React, onMouseEnter or hover is not working as expected
- React Router 4.x - PrivateRoute not working after connecting to Redux
- fireEvent.keyDown not working as expected on my Jest + React Testing Library test
- connect redux function is not working with react-native
- react component state change after ajax call but does not rerender component
- Babel plugin-proposal-decorators not working as expected
- Redux saga debounce and not just delay/cancel
- react-bootstrap not working as expected
- Using React, why is redux saga not intercepting the action?
More Query from same tag
- React: How to access component refs from Redux/Flux actions?
- CSS sliding is overlapping to sticky top menu bar
- TypeScript: What property should I use for Element type?
- ReactJs - How can I add an 'active' class to the nav bar buttons depending on which page is currently being used?
- useContext working not working with nested component
- Axios nested request function return
- how to highlight the selected image?
- How to display a dynamic set of divs depending on how many indexes I have on an array
- Pass value of Input to handleMethod
- React - restrict to numeric/alphanumeric/hexadecimal symbols in text field with max length
- Prevent focused div from scrolling with arrow keys
- how to display a message after submitting a form in React?
- React Update validation with react-hook-form
- Updating the react state/component correctly?
- Meaning of src, public, and build folders
- Clear and Set Interval on one button for Timer
- React Memo still rerenders on state update
- Cannot read property 'map' of undefined [React.js]
- customizing the expansionpanel in material ui and overwriting the styles
- React-Admin: How to edit another Component value after 1 has changed (eg, subtotal+discount=total)?
- can't insert the image dynamically in react
- Meteor React - Publish / Subscribe not working
- TestCafé + React JSX error (unexpected Token)
- React/JavaScript remove something from props.items
- react-create-app test set default headers
- I can't get the html output from draft-js?
- ReactJS: Passing props to map from parent component props are undefined
- Map undefined in ReactJS code for todo list app
- How to make a message appear once email is submitted using React and CSS
- When a key is pressed, the event occurs twice