0
export function* onFetchTree() {
  yield takeLatest('FETCH_TREE', function* () {
    try {
        const response = yield call(fetch, '/myApi/user', {
                    method: 'GET',
                    headers: {
                        accept: 'application/json'
                    }
                })
                const responseBody = response.json();
                yield put({ type: 'SET_TREE', payload: responseBody });
            } catch (e) {
                // yield put(fetchFailed(e));
        return;
            }

  });
}

Learning to work with sagas, stuck on getting the actual data into my redux store. The above code which sends responseBody to the payload gives me a Promise object (because .json() returns that) which is great, except that I can't access the resolved Promise. I ended up on What does [[PromiseValue]] mean in javascript console and how to do I get it but this doesn't seem to work for me. I've tried adding .then() in a few ways, no luck. It seems to prevent the generator function from running at all.

If I just use response I get a Response object, which doesn't have the payload. What am I missing here? How do I get the right payload?

jmargolisvt
  • 5,722
  • 4
  • 29
  • 46

2 Answers2

0

You need to wait for the server to send back the response.

export async function* onFetchTree() {
yield takeLatest('FETCH_TREE', function* () {
    try {
        const response = yield call(fetch, '/myApi/user', {
                    method: 'GET',
                    headers: {
                        accept: 'application/json'
                    }
                })
                const responseBody = await response.json()

                yield put({ type: 'SET_TREE', payload: responseBody )} 
                };

            } catch (e) {
                // yield put(fetchFailed(e));
        return;
            }

});
}
Victor Oliveira
  • 1,109
  • 1
  • 12
  • 29
0

I followed a pattern I found on this page that ended up working for me. I don't fully understand why the fetchTree helper is needed, but it doesn't work without it. https://www.sigient.com/blog/managing-side-effects-with-redux-saga-a-primer-1

function fetchJson(url) {
  return fetch(url, {
        method: 'GET',
        headers: {
            accept: 'application/json'
        }
    })
    .then(response => {
        if (!response.ok) {
            const error = new Error(response.statusText);
            error.response = response;
            throw error;
        }

        return response.json();
    });
}

function fetchTree() {
  return fetchJson('/myApi/user');
}

export function* onFetchTree() {
  try {
    const tree = yield call(fetchTree);

    yield put({ type: 'SET_TREE', payload: tree });
  } catch (e) {
    yield put({
      type: 'ERROR',
      payload: e,
      error: true,
    });
  }
}
jmargolisvt
  • 5,722
  • 4
  • 29
  • 46