Platform: Feature Request: Manage State for dynamically embedded components

Created on 14 May 2018  路  4Comments  路  Source: ngrx/platform

I'm submitting a...


[ ] Regression (a behavior that used to work and stopped working in a new release)
[ ] Bug report  
[X] Feature request
[ ] Documentation issue or request

What is the current behavior?

The same State object is shared among all dynamically added components

Expected behavior:

Every component added dynamically or statically, should have its own copy of the State

Minimal reproduction of the problem with instructions:

The scenario is:

  • I have a component that queries the Store for an array of records. Now, I need to add multiple instances of this component on the same page. All instances share the same state for now. It would be great if there is a way to allow each component to manage its own state.

Thanks
Bilal

All 4 comments

That would kind of work against the concept.
One way to solve your problem, would be to partiton the state, so that each component instance has it's own slice. You would need some id from the component to partition on.

Thanks @phl3x0r, that's the answer I was going to provide as well.

@brandonroberts @phl3x0r
Thanks for your feedback.

After further analysis and reading your replies, I came up with this state structure:

expot const MyState {
    [componentId: number]: {
        entities: { [key:number]: Hero },
        loading: boolean,
        loaded: boolean
    }
}

An example of the above is:

{
    123: {
        entities: {
            1: {
                id: 1,
                name: "Item 1"
            },
            2: {
                id: 2,
                name: "Item 2"
            }
        },
        loading: true,
        loaded: false
    },
    456: {
        entities: {
            1: {
                id: 1,
                name: "Item 1"
            },
            2: {
                id: 2,
                name: "Item 2"
            }
        },
        loading: true,
        loaded: false
    }
}

Now, a component need only access its own slice of state and not all components' states.

So, is it recommended in ngrx/store to define a selector as follows?

export const getComponentState = (key: string) => createSelector(getMyState, (state) => state[key]);

Then, in the component I would do this:

ngOnInit() {
this.store.select(getComponentState(123)).subscribe( compState => this._compState = compState);
}

What do you think gentelmen?

Thanks,
Bilal

Looks fine to me at a first glance.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ghost picture ghost  路  3Comments

dollyshah-02-zz picture dollyshah-02-zz  路  3Comments

gperdomor picture gperdomor  路  3Comments

bhaidar picture bhaidar  路  3Comments

RichardMisiak picture RichardMisiak  路  3Comments