Home > OS >  Why is yield not returning anything in Redux Saga?
Why is yield not returning anything in Redux Saga?

Time:08-10

I'm trying to use Redux Sagas to handle my login action. This is my sagas.ts:

function* loginUserSaga() {
  const user: Login = yield take(actionTypes.LOGIN)
  const { username, password } = user.payload;
  const { data, status } = yield call(() => login({ username: username, password: password }))
  yield put(status === 200 ? loginSuccess(data.token, data.userId) : loginFailed({ message: "Could not log in." }));
}

export function* rootSaga(): Generator {
    yield takeLatest(actionTypes.LOGIN, loginUserSaga)
    yield takeLatest(actionTypes.POST_DRAWING, postDrawingSaga)
    yield takeLatest(actionTypes.GET_WORD_OF_DAY, getWordOfDaySaga)
}

I'm trying to call this login function which sends a POST request using axios as such:

const header = {
    "content-type": "application/json",
}

export const login = (data: LoginRequest) => {
    return axios.request({
        method: "POST",
        url: "http://localhost:3001/api/login",
        headers: header,
        data: data,
    });
};

Using the status, I want to put an action, either loginSuccess or loginFailed:

export const loginSuccess = (token: string, userId: number): LoginSuccess => ({
    type: actionTypes.LOGIN_SUCCESS,
    payload: {
        token,
        userId
    }
})

export const loginFailed = (error: data.Error): LoginFailed => ({
    type: actionTypes.LOGIN_FAILED,
    error: error
})

Why isn't anything being put? From the Network tab of browser, I can see that my express server is returning a response, but the sagas don't seem to work?

Response from express server: enter image description here

CodePudding user response:

I've figured out what went wrong.

export const login = async (data: LoginRequest) => {
    return await axios.request({
        method: "POST",
        url: "http://localhost:3001/api/login",
        headers: header,
        data: data,
    });
};

I had to make this login function async, and await the result from the axios request for it to work.

CodePudding user response:

Call takes the following parameters:

  • your function
  • your arguments

https://redux-saga.js.org/docs/basics/DeclarativeEffects

const { data, status } = yield call(login, { username: username, password: password })
  • Related