Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NGRX root/global state vs cross selecting feature states

Tags:

angular

ngrx

Assuming we have an app with sections for game schedules, players, teams. How would you structure your app/feature states?

My initial thought would be to break these into feature states/modules:

app/
├── games/
│   ├── store/
│   └── games.module.ts
├── players/
│   ├── store/
│   └── players.module.ts
├── teams/
│   ├── store/
│   └── teams.module.ts
└── app.module.ts

With each feature being in charge of CRUD methods for each type of data (games, players, teams).

But in the case of games, you will want to list which teams have played... And you've likely only store references to each team in the games state:

games: {
  game1Id: {
    home: team1Id,
    away: team2Id,
  }
  ...
}

Similarly for viewing teams, you'll want to see the players associated with the team... And again, likely only stored a reference to the playerIds for each team.

Should each of these states/data really be on the global state instead of a feature state where each feature module can select them from a "top-down" approach? Does the feature module structuring even make sense?

Or is it acceptable to "reach across" feature module/states?

Or is there another way that I haven't considered?

like image 541
Empereol Avatar asked Oct 17 '22 10:10

Empereol


1 Answers

As usual, this depends.

Personally, I would say, if you can split it up into different reducers or even features - go for it.

A reducer only knows about its state and not the whole appstate, there are ways to access different slices of the app state:

  • Adding it to your dispatched action
  • Create a reducer handling both of the states, with what redux calls a "case function" reducer

For example:

switch (action.type) {
   case "FOO":
     return fooReducer(state, action);
   case "BAR":
     return barReducer(state, action);
   default:
     return state;
}

To create your view models you can indeed reach across feature modules/states if you're using selectors. For instance, you could create a selector combining multiple smaller selectors from different modules.

More info: Sharing data between modules is peeanuts The Redux Docs

like image 119
timdeschryver Avatar answered Oct 19 '22 02:10

timdeschryver