Search code examples
javascriptreduxaxiossaga

How to access promise data in redux saga


I am trying to grab user data from the server using redux saga. I'm able to successfully get the data and I can see it in the console, but it is in [[PromiseResult]]. I am unable to find any info on how to access this data, or if I am doing something wrong in my saga causing the data to arrive like this.

saga

function* login() {
    try {
        
        const response = yield call(fetch(`${API_URL}/api/current_user`, {
            method: 'GET',
            credentials: 'include',
        }));
        const responseBody = yield response.json();

        yield put(loginUserSuccess(responseBody));
    } catch (error) {
        let message;
        switch (error.status) {
            case 500:
                message = 'Internal Server Error';
                break;
            case 401:
                message = 'Invalid credentials';
                break;
            default:
                message = error;
        }
        yield put(loginUserFailed(message));
        // setSession(null);
    }
}

payload I can console.log

Promise {<fulfilled>: {…}}
__proto__: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: Object
{
credits: 0
date: "2020-12-21T22:23:43.461Z"
email: "[email protected]"
password: "$2a$10$W.GOdcdyfphcazW.9flFTeoQ4s/3khfZOv2dkyJ2Bg/gl0pIZRtHu"
plan: 1
verified: false
__v: 0
_id: "5fe1206f4a30e03194bfdf0b"
}
__proto__: Object

Solution

  • That is not how call works first argument is a function and second is an array of argument(s) you want to pass to that function. The following should work:

    const response = yield call(fetch, [
      `${API_URL}/api/current_user`,
      {
        method: 'GET',
        credentials: 'include',
      },
    ]);
    const responseBody = yield call(() => response.json());