Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redux sharing actions between components

I'm building a mobile app with react-native and redux, I'm organizing my project structure by features in this way:

Component1/
---Component1Actions.js
---Component1Reducer.js
---...
Component2/
---Component2Actions.js
---Component2Reducer.js
---...

In my opinion this kind of project structure is amazing for many reasons, first of all for its great scalability. Only problem I have come across so far is when 2 different components have to dispatch the same actions (such as a simple text change in a textbox).
It wouldn't make sense to rewrite the exact same action in 2 different files and I also know that importing an action from one component to another component is really a bad practice. I thought about keeping these kind of "shareable" actions in a global module and then import them in the various components but I'm not sure if it is a good practice.
I would like to know the best way to handle this kind of situations.
Thanks in advance.

like image 213
Alessandro Messori Avatar asked Jul 31 '16 00:07

Alessandro Messori


People also ask

How do I share a state between components in React Redux?

Another way to share data between multiple components is to use a state management solution. A popular state management solution for React apps is Redux and React-Redux. In index. js , we have the rootReducer with that takes the state value and return the latest value of the store based on the action type we dispatch.

Can I dispatch an action in reducer?

Dispatching an action within a reducer is an anti-pattern. Your reducer should be without side effects, simply digesting the action payload and returning a new state object. Adding listeners and dispatching actions within the reducer can lead to chained actions and other side effects.

Does Redux support multiple actions?

Well, no matter what you pass to dispatch , it is still a single action. Even if your action is an array of objects, or a function which can then create more action objects!


1 Answers

You can handle the same "ACTION_TYPE" in multiple reducers.

... actions are by design global. They are not meant to be tied to a particular reducer (Dan Abramov)

You could handle an "LOGOUT" action in all your reducers, which would just return the initial state.. and set the application to defaults

for example..

const postReducer = (state = initial, action) => {
  swtich(action.type) {
  ...
  case "LOGOUT": 
    return initial 
  default: 
    return state
  }
}
like image 174
webdeb Avatar answered Oct 31 '22 15:10

webdeb