Reputation: 163
I'm a newbie to redux-saga. Currently I'm working on a simple login example. Take a look at these function:
function sendLoginRequest(data) {
const headers = { 'Accept': 'application/json' };
const url = LOGIN_URL;
const serialize = new FormData(data.event.target);
const loginData = {
username: serialize.get('email'),
password: serialize.get('password'),
client_secret: APP_SECRET_KEY,
client_id: APP_SECRET_ID,
grant_type: PASSWORD_GRANT_TYPE,
scope: '*',
}
return axios({
method: 'POST',
url: url,
data: loginData,
headers: headers,
});
}
export function* loginRequest(data) {
yield takeLatest(LOGIN_REQUEST, data => {
const response = sendLoginRequest(data);
console.log(response);
response
.then(function* (data) {
console.log(data);
yield put(LOGIN_SUCCESS, data.data);
})
.catch(function* (err) {
console.log(err);
yield put(LOGIN_FAILURE, err.response);
});
});
}
It's work perfect if I run middleware like this:
const sagaMiddleware = createSagaMiddleware();
const store = createStore(
rootReducer,
applyMiddleware(sagaMiddleware)
);
sagaMiddleware.run(loginRequest);
But then I add a new rootSaga:
export default function* rootSaga() {
yield all([
fork(loginRequest),
fork(loginSuccess),
fork(loginFailure)
]);
}
And I run the rootSaga instead of loginRequest saga:
const sagaMiddleware = createSagaMiddleware();
const store = createStore(
rootReducer,
applyMiddleware(sagaMiddleware)
);
sagaMiddleware.run(rootSaga);
And now these new code doesn't work at all.
when I try to console.log(response);
in loginRequest generator function, it's shown that the promise has been resolved. And it doesn't run the then-catch.
Can anyone help me clear this out? Thank you~
Upvotes: 0
Views: 1671
Reputation: 1368
Please try this:
export function* loginRequest(data) {
yield takeLatest(LOGIN_REQUEST, data => {
const response = yield call(sendLoginRequest, data);
if (response.status >= 200 && response.status < 300) {
yield put(LOGIN_SUCCESS, data.data);
return;
}
yield put(LOGIN_FAILURE, err.response);
});
}
The thing to note is sendLoginRequest
returns a promise. redux-saga
is designed to work with promises without using .then()
. You can yield call()
any function that returns a promise and redux-saga
will wait for the promise to resolve before executing the next line of code.
Upvotes: 3