Search code examples
reactjspromisereduxredux-saga

Promises in redux-saga


I found the same question here, but without a proper answer I am looking for.

I am developing a simple application with CRUD operations. On the edit page, after the component gets mounted (componentDidMount()), the app dispatches an action to retrieve a specific post details:

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

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

Right now, without a callback/Promise, I ended up with defining a new state in store (like post_edited) and connect/map it to props in the component for edit page.

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


Solution

  • Could you please provide more information about your issue? I'm not sure if I understand your issue properly, but the common practice is:

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