Reputation: 2087
I'm trying (learning) to make an asynchronous post request using redux-saga, but i'm getting a synchronous behavior.
this is the code i'm using:
import {AUTH_REQUEST} from '../constants/authentication';
import {authSuccess, authError} from '../actions/login';
import {takeEvery, call, put, fork, all} from 'redux-saga/effects';
import axios from 'axios';
const authenticate = (username, password) => {
axios
.post('http://localhost:8000/api/auth/login/', {username, password})
.then((response) => {
console.log('RESPONSE: ', response.data);
return response.data;
})
.catch((error) => {
throw error;
});
};
function* watchAuthRequest({username, password, resolve, reject}) {
try {
const result = yield call(authenticate, username, password);
console.log('RESULT', result);
yield put(authSuccess(result));
yield call(resolve);
} catch (error) {
yield put(authError(error));
yield call(reject, {serverError: 'Something bad happend !'});
}
}
const authSaga = function* authSaga() {
yield takeEvery(AUTH_REQUEST, watchAuthRequest);
};
export default function* rootSaga() {
yield all([
fork(authSaga),
]);
};
and when i submit the form (i'm using redux-form), this is why i get in my console logs:
RESULT: undefined
RESPONSE: Object {user: Object, token: "04a06266803c826ac3af3ffb65e0762ce909b07b2373c83b5a25f24611675e00"}
and even the authSuccess
action is getting dispatched with an empty payload (result
)
am i doing something wrong here ?
Upvotes: 2
Views: 542
Reputation: 2062
You're missing a return
:
const authenticate = (username, password) => {
return axios
.post('http://localhost:8000/api/auth/login/', {username, password})
.then((response) => {
console.log('RESPONSE: ', response.data);
return response.data;
})
.catch((error) => {
throw error;
});
};
Upvotes: 4