2

I have a scenario where we are adding an item to a list using by dispatching an action that calls a reducer to update the state, and then trying to grab that updated list immediately after. Here's a simple example:

yield put(addItem(newItem));
const items = yield select(getItems);
// do something with items

My question is, is the new item guaranteed to be in items, or is this a race condition? I understand that yield is waiting for the action to be dispatched, but I'm concerned that the action will be dispatched which will trigger the saga to continue, then the selector is called, and then the reducer actually updates the state. Is this a valid concern? Or will the put not even return until the reducer has run first?

I understand I can simply call select first, dispatch the action, and then locally within the saga update items like this:

const items = yield select(getItems);
yield put(addItem(newItem));
const updatedItems = [
    ...items,
    newItem
];
// do something with items

However, I would like to avoid this because it would essentially be recreating the reducer logic within the saga, and require any changes within the reducer to also be reflected in the saga. It would be cleaner to select the updated object from the state after put.

stickboi
  • 21
  • 1
  • 3
    Put should update the state before yielding back to the saga, according to the docs. https://redux-saga.js.org/docs/api/#putaction – Håken Lid Feb 17 '21 at 17:57

0 Answers0