Elcid_91
Elcid_91

Reputation: 1681

Clarification on Stores in Reactjs-Redux

I am currently learning how to use Redux in my ReactJS application and all the tutorials I've seen lead me to believe that there can only be one store in Redux. In a real-world applications, you may have multiple streams of data coming from a REST api or some other source. So, for example, I may be looking at a list of customers in one component and a list of projects in another and list of users in yet another. My question is: Does Redux allow you to create a store for each entity with it's own reducer and actions? For example, a customer store, a project store and user store? If not how would one organize this in a single store without everything getting convoluted? Thanks.

* EDIT * So my state would look something like:

let initalState={
     customers:{
          data:[]
          ...
     },
     projects:{
          data:[]
          ...
     }
     users:{
          data:[]
          ...
     }
}

Upvotes: 0

Views: 28

Answers (1)

Olivier Boissé
Olivier Boissé

Reputation: 18113

I think that combinereducers is what you are looking for.

As your app grows more complex, you'll want to split your reducing function into separate functions, each managing independent parts of the state.

The combineReducers helper function turns an object whose values are different reducing functions into a single reducing function you can pass to createStore.

Imagine you want to manage the customers, projects and users.

You will get one reducer per feature :

const customersInitialState = {data:[], ...}
export default function customersReducer(state = customersInitialState , action) {
  switch (action.type) {
    case 'ADD':
      return {...state, data: [...state.data, action.payload]}
    default:
      return state
  }
}

Then you will combine all theses reducers into a single one

export default combineReducers({
  customers: customersReducer,
  projects: projectsReducer,
  users: usersReducer
})

const store = createStore(reducer)

Finally the state of your store will be like this :

{
  customers: {data: [], ...},
  projects: {data: [], ...},
  users: {data: [], ...},
}

Upvotes: 1

Related Questions