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.
First option :
As in the tutorial, I should have 1/ action INCREMENT
and one DECREMENT
. And in the reducer it would ++
or --
.
Second option
I should have only one ActionType and pass the increment in the payload.
store.dispatch({ action: "INCREMENT", payload: { increment: -1 } })
. And I could have 2 actions
export const decrementCounter = () => {
store.dispatch({ action: "INCREMENT", payload: { increment: -1 } })
};
export const decrementCounter = () => {
store.dispatch({action: "INCREMENT", payload: {increment: -1}})
}
Or another way ?
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.