S
S
Seva2018-02-02 16:21:07
React
Seva, 2018-02-02 16:21:07

Why is redux-saga not working?

Hey! Everything seems to be simple:

const getAccounts = function* getAccounts() {
  while (true) {
    const request = yield take(GET_ACCOUNTS);
    const userID = request.data.userID;
    try {
      response = yield call(AccountsService.getAccounts, userID);    // тут асинхронный вызов
      yield put({ type: ACCOUNTS_RECEIVED, response });
    } catch (error) {
      return false;
    }
  }
}

Reducer
export const accounts = (state = INITIAL_STATE, action) => {
  switch (action.type) {
    case ACCOUNTS_RECEIVED:
      console.log(action);  // тут action.response - undefined
      return { ...state, accounts: action.response.Items[0].accounts };
    case ADD_ACCOUNT:
      return { ...state, accounts: [ ...state.accounts, action.newAccount ] };
    default:
      return state;
  }
};

The saga does not wait for the asynchronous function to return a value, it immediately dispatches ACCOUNTS_RECEIVED with an empty response. Why?
Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2018-02-02
@Zewkin

You have an error here:

export const getAccounts = (userID) => {
  fetch(`${BASE_URL}/users/${userID}/accounts/`).then(resp => {
    resp.json().then(accounts => accounts.Items[0].accounts);
  })
}

You don't return anything.
Fix like this:
export const getAccounts = userID =>
  fetch(`${BASE_URL}/users/${userID}/accounts/`).then(resp => {
    resp.json().then(accounts => accounts.Items[0].accounts);
  });

And better use axios instead of fetch The Service
entity is useless in this architecture, import and use the function directly:
response = yield call(getAccounts, userID);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question