Roffulus
Roffulus

Reputation: 33

React-redux state undefined error in my reactJS Component

This is my initial state :

 export const initialState = {
  currencieList: [],
  currentPage: 1,
  pageCount: 1,
  itemsPerPage: 20,
};

Here is my redux-saga with which I want to trigger an action:

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

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

Getcurrencies reducer :

 export const getCurrencies = (currencies) => {
  return {
    type: actionTypes.LOAD_DATA_ASYNC,
    payload : currencies,
  };
};



 case actionTypes.LOAD_DATA_ASYNC:
  return {
    ...state,
    currencieList: action.currencies,
  };

And here is how I'm calling getcurrencies in my component :

     componentDidMount() {
    const { getCurrencies} = this.props.actions
    setInterval(() => {
      getCurrencies();
    }, 30000);
  }

Problem ---------

The problem is whenever componentDidMount executes getcurrencies. I'm getting error that can not slice .... undefined

const { currencieList, currentPage, itemsPerPage } = this.props;
const indexOfLastItem = currentPage * itemsPerPage;
const indexOfFirstItem = indexOfLastItem - itemsPerPage;
const currentItems = currencieList.slice(indexOfFirstItem, indexOfLastItem);

I console.log-ed currencieList and before render it is empty array is it should be but after render it becomes undefined and I have no idea why. I also checked if I'm getting data correctly in my redux-saga and it is correct.I'm retrieving the data it is not undefined Any suggestions please?

Upvotes: 0

Views: 606

Answers (1)

Priyanka Panjabi
Priyanka Panjabi

Reputation: 441

In ComponentDidMount write it like :

componentDidMount() {
const { getCurrencies} = this.props.actions
setInterval(() => {
  getCurrencies([]);
}, 30000);

} and then in your saga write it like :

 yield put(getCurrencies(data.data);

and then in reducer write :

case actionTypes.LOAD_DATA_ASYNC:
  return {
    ...state,
    currencieList: action.payload,
  };

Upvotes: 1

Related Questions