Search code examples
reactjsreduxredux-saga

Get Data from api in redux-saga reactJS


I'm trying to fetch data from API In my redux-saga but I'm getting following error from here const {body: {data}} =yield getData() in my redux-saga:

cannot read property body of udefined

Here is my API Function:

    export function* getData() {
    yield agent
        .get(
            "https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?CMC_PRO_API_KEY=xxx"
        )
        .then((res) => {
            getCurrencies(res.body.data);
            console.log('--------res.body.data', res.body.data);
            setPageCount();
        })
        .catch((err) => {
            console.log(err);
        });
}

.then is returning the data itself,So it is not undefined

Here is my redux-saga itself:

    function* loadDataAsync() {
  console.log("SAGAS WORKS");
    yield delay(5000);
  try {
    const {body: {data}} =yield getData()
    console.log(data)
    yield put({type:"LOAD_DATA_ASYNC_SUCCESS"});
  } catch (err) {
    console.log(err)
    yield put({type:"LOAD_DATA_ASYNC_ERROR"})
  }
}

export function* watchLoadDataAsync() {
  yield takeLatest("LOAD_DATA_ASYNC", loadDataAsync);
}

Any solutions please?


Solution

  • You need to use call to get the data back from your asynchronous action

    function* loadDataAsync() {
      console.log("SAGAS WORKS");
        yield delay(5000);
      try {
        const {body: {}} = yield call(agent.get, "https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?CMC_PRO_API_KEY=xxx");
        console.log(body.data);
        // Call your other functions here
        getCurrencies(body.data);
        setPageCount();
    
        yield put({type:"LOAD_DATA_ASYNC_SUCCESS"});
      } catch (err) {
        console.log(err)
        yield put({type:"LOAD_DATA_ASYNC_ERROR"})
      }
    }
    

    For more information check out the official docs for call