angular-redux / store

Angular 2+ bindings for Redux
MIT License
1.34k stars 202 forks source link

How to bind component to elements in array #490

Closed marxxxx closed 6 years ago

marxxxx commented 6 years ago

This is a...

I'm pretty new to redux and i was thinking about a way to faciliate state management in my project.

I read the article about fractal stores (https://github.com/angular-redux/store/blob/master/articles/fractal-store.md) and see it useful when i have components bind to elements in a list of objects of the same type.

The example given in the article however depends on having the state shaped in a way to make the single elements accessible by a property (the userId in the example) like this:

{
 "bob": {
 "firstName": "bobby",
...
},
"alice": {
 "firstName": "alice",
 ...
 }
}

How could i use redux when my datastructure looks more like this:

users: [
{
 userId: "bob",
 firstName: "bob"
},
{
 userId: "alice",
 firstName: "alice"
}
]

This would be a more typical way i would receive data from a backend service.

Or would redux only work if i apply transformations after receiving the data to make if fit into the property-syntax ?

Thank you very much!

Kind regards Markus

e-schultz commented 6 years ago

In this case, when configuring your substore it would be more like:

this.subStore = this.ngRedux.configureSubStore(
      ['users'],
      userComponentReducer);

    // Substore selectons are scoped to the base path used to configure
    // the substore.
    this.users$ = this.subStore.select(state=>state); // basically returning the entire list of users

if I'm understanding your question correctly.

marxxxx commented 6 years ago

Thank you for your reply, e-schultz!

As far as i understand, your suggestion would map the whole list of users to my component.

However i would like to map a single element from the user-list to my component. For example i get a list of users from my backend, put it in my application state and display them in various places. All users in the application state will be displayed in a list. Specific users should be displayed in cards in another place of my UI. So the component displaying a card for a single user should get mapped to one of the elements in the user-array in my state.

If a property changes in the user-array in the application state, every component displaying this user should get updated.

marxxxx commented 6 years ago

well, after thinking further about it: would it be possible to map a single user element to a component using:

this.user$ = subStore.select( u => u.userId == userId);

?

e-schultz commented 6 years ago

Could do something like:

this.user$ = subStore.select( users => users.find(user=>user.userId === userId))
marxxxx commented 6 years ago

Cool thanks i'll give this a try!