score:0

it's been a while since i worked with sagas but here is some code that will give you a general idea how to wait for a dispatched action.

the way it works is that when you fetch and want to wait for it to fail or succeed you give the fetch action an id, then you can pass that to the waitfor function while simultaneously dispatch the action.

if you don't want or need to wait for it then you can just dispatch the action without an id and it'll still work:

const addid = (id => fn => (...args) => ({
  ...fn(...args),
  id: id++,
}))(0);
const withid = ({ id }, action) => ({ action, id });

function* waitfor(id) {
  const action = yield take('*');
  if (action.id === id) {
    return action;
  }
  return waitfor(id);
}

function* globalsearchrequestsaga(action) {
  const { query } = action;
  console.log(
    `searching subscriptions and users for : ${query}`
  );
  try {
    //add id to action (id is unique)
    const action = addid(fetchusersrequest, query);
    //dispatch the action and then wait for resulting action
    //  with the same id
    yield put(action);
    const result = yield waitfor(action.id);
    // call for the subscriptions (leaving it out for simplicity in this example)
    yield put(globalsearchsuccess(query));
  } catch (error) {
    console.log(`error: ${error}`);
    yield put(globalsearchfailure(error.message));
  }
}

export function* fetchusersrequestsaga(action) {
  const { query } = action;
  const path = `${root}/users`;
  try {
    const users = yield axios.get(path, {
      crossdomain: true,
    });
    yield put(//add original id to success action
      withid(action, fetchuserssuccess(query, users.data))
    );
  } catch (error) {
    console.log(`error : ${error}`);
    yield put(
      withid(//add original id to fail action
        action,
        fetchusersfailure(query, error.message)
      )
    );
  }
}

score:2

the put function is a non-blocking action. it won't wait till the promise/api request resolves.

i would suggest you to just call sagas directly instead of dispatching actions.

try {
   yield call(fetchusersrequestsaga, query);
   yield call(globalsearchsaga, query); // or whatever its called
}

call is a blocking action. it will wait until the request finishes, so both if your calls will execute in proper order.


Related Query

More Query from same tag