Promises in the Reduction Saga

I found the same question here , but without the proper answer I'm looking for.

I am developing a simple application with CRUD operations. On the editing page, after installing the component ( componentDidMount()), the application sends an action to receive certain information about the message:

dispatch({ type: FETCH_POST, id: 'post-id' })

I am using redux-saga and want the above call to return Promise so that I can access the API response.

Right now, without callback / Promise, I ended up defining a new state in the store (for example post_edited) and connected / matched it with the details in the page editing component.

What would be the best way to deal with this situation?

+4
source share
1 answer

Could you provide additional information about your problem? I'm not sure if I understand your problem correctly, but the general practice is this:

API.js

function apiCallToFetchPost(id) {
  return Promise.resolve({name: 'Test});
}

postSaga.js

function* fetchPostSaga({id}) {
  try {
    const request = yield call(apiCallToFetchPost, id);
    // -> in post reducer we will save the fetched data for showing them later 
    yield put({type: FETCH_POST_SUCCESS, payload: request}); 
  } catch (error) {
    yield put({type: FETCH_POST_SUCCESS_FAILURE, error})
  }
}

export function* onBootstrap() {
  yield takeLatest(FETCH_POST, fetchPostSaga);
}
+7
source

Source: https://habr.com/ru/post/1670120/


All Articles