Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic Components with React Redux

I am struggling a bit with the concept of global state and reusable components in redux.

Let's say I have a component that's a file-selector that I want to use in multiple places inside my applications state. Creating action/reducers leads to a lot of bloat as I have to handle states with dynamic suffixes and other weird things that just don't really strike me as a smart way to go about things.

What's the general consensus on these things? I can only see two solutions:

  • Make the file-selector component have local state (this.setState/this.getState)

  • Make the file-selector be part of the global state but in it's own unique reducer that I can read from once the operation of the component is done?

Any ideas / best practices? Thanks.

Update: To clarify the file selector I am describing is not a simple component that works purely on the client side but has to fetch data from the server, provide pagination as well as filtering etc.. That's why I'd also like to reuse most of the client/server interaction. The views that display this component are of course dumb and only display values from the state - but how do I reuse the actions/reducers in multiple places around the application?

like image 698
Tigraine Avatar asked Mar 06 '17 08:03

Tigraine


1 Answers

Have your reducer handle multiple instances of your component state. Simply define some "unique" ID for each instance of your FileBrowser component when it appears in the app, and wrap your current state in an object with this uniqueIds as keys, and your old complex state as value.

This is a technique I've used multiple times. If all your FileBrowser are known at compile time, you can even setup the initial state before running your app. If you need to support "dynamic" instances, simply create an Action that initializes the state for a given id.

You didn't provide any code, but here's a contrived example for a reusable Todo reducer:

function todos(state={}, action){
  switch(action.type){
    case 'ADD_TODO':
      const id = action.todoListId
      return {
         ...state,
         [id]: {
            ...state[id],
            todos: [ ...state[id].todos, action.payload ]
         }
      }
      // ... 
  }
}
like image 123
CharlieBrown Avatar answered Sep 25 '22 16:09

CharlieBrown