Samuel Wong
Samuel Wong

Reputation: 13

redux practice for 2 frequent challenges

I want to learn a good practice from others, please share how you do this :

Task:
suppose there are 2 reducer: boy : "Tom", girl : "Mary"

a function swap() is going to swap those 2 values, such as boy : "Mary", girl : "Tom"

Here is the plan :

dispatch 2 action :

{type: BOY_EDIT, value: "Mary"},
{type: GIRL_EDIT, value: "Tom"}

and the cons is:

  1. reducer can not read other reducers' value, and you need to pass them through actions

  2. there are two actions for two reducer, as someone said don't mess two reducer by one action which will cause maintainability reducing

what do you think? A easy and good way to solve these 2 frequent challenges ?

Ps: redux-saga select() may be a good solution ?

#

Addition:

Sorry for making unclear question, I understand that above scenario can solved by combining reducers as 1 But my assumption is NOT combining them

This is because I just simplify the scenario above And the real situationis, some cases you need to do some operation in reducer and depend on other reducers' value.

I would like to know other's practices on facing this challenge

Upvotes: 0

Views: 65

Answers (2)

Subin Sebastian
Subin Sebastian

Reputation: 10997

Use a single reducer say an object which has both boy and girl properties and a single action say ‘SWAP’ to swap the property values.

Initialise the reducer with an initialValue so that default state is created.

Within SWAP action

return {boy: state.girl, girl: state.boy}

Upvotes: 0

Yossi
Yossi

Reputation: 6027

Map both girl and boy to the same container, and dispatch a single action. I don't see why this is bad practice. On the other hand, creating two actions for this is a bad practice, since after 2 years you will need to change your code, forget that the two actions are tied together, and change only one.

If I am not wrong, redux itself dispatches a single action when it starts, something called INIT or something similar, I don't have a running system in front of me now, that is dispatched to all reducers... I also use INIT actions of my own, for example, when a user logs out of the application, to clear her/his data.

Upvotes: 1

Related Questions