Roffulus
Roffulus

Reputation: 33

Fetch api data in redux-saga

I want to fetch api data with redux-saga .

Here is how I call my api :

 export const getData = () => {
    agent
      .get(
        "https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?CMC_PRO_API_KEY=XXX"
      )
      .then((res) => {
       console.log(res.body.data)
      })
      .catch((err) => {
        console.log(err);
      });
  };

Here is my redux-saga :

import { takeLatest, put } from "redux-saga/effects";
import { delay } from "redux-saga/effects";

function* loadDataAsync() {
  yield delay(500);
  yield put({ type: "LOAD_DATA_ASYNC" });
}

export function* watchloadData() {
  console.log("Im working buddy");
  yield takeLatest("LOAD_DATA", loadDataAsync);
}

The problem Is I don't really know how to fetch data through redux-saga,I tried to do research but none of the information seemed to satisfy me. Could you please give me some suggestions?

Upvotes: 0

Views: 66

Answers (1)

Tilak Madichetti
Tilak Madichetti

Reputation: 4346

The problem Is I don't really know how to fetch data through redux-saga,

No, the problem is you don't really know function generators in javascript.

Anyways if I were to architect that piece of code I would do something like this:

export function* getData(){
 yield agent
  .get(
    "https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?CMC_PRO_API_KEY=XXX"
  )

};

And then:

function* loadDataAsync() {

  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_FAILED" });

  } 

}

Upvotes: 2

Related Questions