NgRx Entity Adapter - adding a second class?

45 Views Asked by At

I have a working NGRX state configuration based around an existing class, lets call it Class1.

I want to use the global state to look after another class, Class2.

I don't know how to lay this out. Do I need to use a second EntityAdapter? Do I just create a new reducer file for this second class?

This is what I have already in my existing reducer:

import { createReducer, on } from '@ngrx/store';
import { ActionTypes } from '@state/actions/action-types';
import { createEntityAdapter, EntityState } from '@ngrx/entity';
import { Class1 } from '../../models/class1';
import { Class2 } from '../../models/class2';


export interface MyState extends EntityState<Class1>{
  status: 'loading' | 'error' | 'success';
  errorMsg: string;
}

export const adapter = createEntityAdapter<Class1>();

// If I want to use a second class, do I just create a second adapter?
export const adapter2 = createEntityAdapter<Class2>();

export const initialState = adapter.getInitialState({ 
  status: 'loading', 
  errorMsg: '',
});


export const stuffReducer = createReducer(
  initialState,

  on(ActionTypes.StockpileActions.loadClass1Stuff, (state, action) =>
    adapter.setAll(action.stuff, {...state, status: 'success', errorMsg: ''})
  ),

    // Can I use the second adapter to access the related actions for that class?
  on(ActionTypes.StockpileActions.loadClass2Stuff, (state, action) =>
    adapter2.setAll(action.stuff, {...state, status: 'success', errorMsg: ''})  
  ),
  
);

export const { selectAll } = adapter.getSelectors();

Any help is appreciated! I am fairly new to NgRx and redux state management.

I should point out Class 2 is in no way related to Class1, so I can't really extend them and treat them as a combined class.

0

There are 0 best solutions below