Istvan Orban
Istvan Orban

Reputation: 1685

Fetch is empty Redux Saga

I just started learning Redux Saga 5 mins ago

My saga:

import axios from "axios";
import {call, put, takeLatest} from "redux-saga/effects";
import {
    USERS_FETCH_REQUESTED,
    USERS_FETCH_SUCCEEDED,
    USERS_FETCH_FAILED
} from 'actions/constants'

function *fetchUsers(action) {
  try {
    const response = yield call(fetch, 'https://jsonplaceholder.typicode.com/users');
    const data = response.json();
    console.log(data)
    yield put({type: USERS_FETCH_SUCCEEDED, payload: data});
  } catch (e) {
    yield put({type: USERS_FETCH_FAILED, payload: e.message});
  }
}

function* mySaga() {
    yield takeLatest(USERS_FETCH_REQUESTED, fetchUsers);
}

export default mySaga

for some reason my SUCCES_FETCH's payload is just an empty object, BUT the log give back 10 10 items.

What am I doing wrong?

Upvotes: 1

Views: 691

Answers (1)

mpontus
mpontus

Reputation: 2193

response.json() returns a promise, you need to wait for the promise to resolve to get to the items.

const data = yield call([response, 'json']);

This will produce an effect which calls response.json() and feeds the results back into the saga after the promise resolves.

Upvotes: 3

Related Questions