Home > other >  Calling multiple reducers inside the same dispatch in redux toolkit with the comma operator doesn�
Calling multiple reducers inside the same dispatch in redux toolkit with the comma operator doesn�

Time:11-25

According to MDN:

The comma operator (,) evaluates each of its operands (from left to right) and returns the value of the last operand.
This lets you create a compound expression in which multiple expressions are evaluated,
with the compound expression's final value being the value of the rightmost of its member expressions.
This is commonly used to provide multiple parameters to a for loop

So I thought that something like this would work:

const gameData = useDispatch();
    gameData((
    readGameAnswers(props.gameAnswers),
    readGameAnswersImage(props.gameAnswersImages as string[]),
    readCorrectAnswer(props.correctAnswer)));

(where the 3 read functions are reducers defined on the store))

The behavior is not what I expect though - only the last read is being called. Why is this happening? Shouldn't it work according to the definition of the comma operator?

CodePudding user response:

Unfortunately, no, that won't work because each method call just provides an action, and because of the behavior of the commas, only the last one is returned to the dispatcher (gameData). What you're looking for is an action creator which combines multiple reducer calls into one.

I believe this question has the answer you're seeking!

  • Related