Stefdelec
Stefdelec

Reputation: 2811

How should I organize my actionType with Redux to be maintainable over time and dev?

I am using redux for a project. I take the "increment/decrement a counter" basic tutorial as an example. I wonder how I should organize my action type in order to be able to maintain and scale my app in real life.

Or another way ?

Upvotes: 0

Views: 148

Answers (2)

Aditya Loshali
Aditya Loshali

Reputation: 66

I assume you used create-react-app to create your project .

  • Make a folder ' actions ' in the ' src ' directory, where your App.js and Index.js are located. In actions folder create two files, 1- actionTypes.js and 2- actionCreators.js .

  • Define your action types as constants in the actionTypes.js file, so that their value does not mistakenly gets changed and export them from there .

  • In actionCreators.js, import your action types and define your action creators using them.

  • in src folder , create another folder named redux / store / reducers . Any name would do . then in it create a file reducers.js . define your reducers there . and import action types. make a switch-case block to check for the action type and define corresponding code to execute i.e ++ or -- .

DO-NOT send the payload as -1 or +1 . that can work but is a bad practice.

DO check the redux documentation. They have a fantastic documentation.

Upvotes: 1

frontendgirl
frontendgirl

Reputation: 787

It depends how do you see your architecture should be built. Both ways are good, first one more reflect the real events that are happening in your app (like click on "+" button near input, should trigger "INCREMENT" action, and click on "-", should trigger "DECREMENT"), so in this case stores contains more logic, because they are directly knowing how to reflect on the events that are happening in UI.

In case of usage second option, first of all, it should have a different name (something like "CHANGED") as you are expecting both be able to decrement or increment here. In this case, the connection between the stores and UI events are weaker, and some of the logic is stored in action type itself (in this case - for how much value should change).

The more logic is left to store and reducers, the better, as reducers are pure, what allows write tests for them easier.

Upvotes: 0

Related Questions