Search code examples
reactjsredux-saga

How to wait for action and API call to complete using redux saga?


I am dispatching an action which makes an API call to a backend and then I am updating the store. I need to access props on the next line after the action dispatch in my React Component.

this.props.getUser();

//need the user here
console.log(this.props);

Action looks like this in my actions.js file and is being mapped to props in my react component

const getUser = () => ({
  type: 'GET_USER'
});

The action goes into the Saga.js file which calls a service file with the API call. If this is not sufficient information please let me know and I will elaborate more on it.


Solution

  • In redux-saga, yield is the keyword that waits for the API call to finish, and returns our results. The basic pattern of using it for API calls looks like this:

    import { call, put, takeEvery, takeLatest } from 'redux-saga/effects'
    import Api from '...' <-- the path to your API endpoint
    
    // will be fired on GET_USER actions
    function* getUser(action) {
       try {
          // redux-saga will wait till the endpoint function will finish and return
          const user = yield call(Api.getUser);
          // In your reducer: you're returning the user 
          yield put({type: "GET_USER_SUCCEEDED", user: user});
       } catch (e) {
          // Or an error message 
          yield put({type: "GET_USER_FAILED", message: e.message});
       }
    }
    
    // the saga you link to your middle-ware setup where you setting up the store.
    function* rootSaga() {
      yield takeEvery("GET_USER", getUser);
    }
    
    

    Note that you'll want redux to handle request/error/success. then you'll need the following cases GET_USER, GET_USER_FAILED & GET_USER_SUCCEEDED, respectively.