Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
  • Jul 26 05:47
    amithegde commented #20
  • Jul 26 05:46
    amithegde commented #20
  • Jul 06 09:12
    the0rem commented #20
  • Oct 15 2019 16:45
    johannesjo commented #20
  • Sep 21 2019 04:04
    JimTheMan closed #16
  • May 04 2019 00:15
    felixunivers edited #17
  • Apr 29 2019 21:30
    felixunivers opened #17
  • Apr 10 2019 21:15
    rezord opened #16
  • Jan 31 2019 20:44
    alex-okrushko commented #1511
  • Jan 31 2019 20:21
    brandonroberts edited #1538
  • Jan 31 2019 20:20
    brandonroberts edited #1538
  • Jan 31 2019 20:18
    brandonroberts labeled #1538
  • Jan 31 2019 20:18
    brandonroberts labeled #1538
  • Jan 31 2019 20:18
    brandonroberts opened #1538
  • Jan 31 2019 12:11
    timdeschryver closed #1536
  • Jan 31 2019 12:11
    timdeschryver commented #1536
  • Jan 31 2019 12:08
    timdeschryver closed #1537
  • Jan 31 2019 12:08
    timdeschryver commented #1537
  • Jan 31 2019 11:59
    olefrank commented #1036
  • Jan 31 2019 11:59
    olefrank commented #1036
RoboZoom
@RoboZoom
it's very doable do it through the route, just some different structure
Adam Marshall
@adamm-monek
yeah I think I need to trigger it all via the route, in case you bookmarked it or something
RoboZoom
@RoboZoom
yup
Adam Marshall
@adamm-monek
great... I think I have everything I need, thank you for your help!
RoboZoom
@RoboZoom
sure thing! Good luck!
Derek
@derekkite
@adamm-monek I found the router store useful because it replaced code in all my container components where I read the router data, dispatched an action, dealt with no parameters etc.
Adis Bajric
@abajric1
What is good practice when i want to update say input field both from backend (api call) and frontend .. can i use dispatch action on (ngModelChange) ?
matrixbot
@matrixbot
@this-is-me:matrix.org if you have the option, you might also consider dispatching it only after submit, but sure: why not
@this-is-me:matrix.org you could consider rate limiting if it is a text field, though
Adis Bajric
@abajric1
yeah diispatching on (blur) is way convinient ty
Nurali Khoja
@TheCoderFish

I am trying to create a facade method which will return me the entity from the input id


getUserById(userId: string): Observable<User> {
    return this.store.pipe(select(selectUserById, { userId }));
}

getUser(userId: string): Observable<User> {
    this.store.dispatch(UserActions.loadUser({ userId }));
    return this.getUserById(userId);
  }

Action

export const loadUser = createAction(
  '[Users] Load User',
  props<{ userId: string }>()
);

Effect

loadUser$ = createEffect(() => this.actions$.pipe(
        ofType(UserActions.loadUser),
        switchMap(({ userId }) => this.userApiService.getUser(userId).pipe(
            map((user: User) => {
                if (user?.id) {
                    return UserActions.loadUserSuccess({ user });
                }
            }),
            catchError((error) => of(UserActions.loadUserFailure({ error: { errorMessage: UserErrorMessages.LOAD_ERROR, details: error?.error?.details, type: UserErrors.LOAD_ERROR } }))
            )),
        ))
    );

Reducer

  on(UserActions.loadUser,
        (state) => ({
            ...state,
            callState: LoadingState.LOADING
        })
    ),
    on(UserActions.loadUserSuccess,
        (state, action) => adapter.setOne(action.user, {
            ...state,
            callState: LoadingState.LOADED
        })
    ),
    on(UserActions.loadUserFailure,
        (state, { error }) => {
            return ({
                ...state,
                callState: error
            });
        }),

Selector

export const selectUserEntities = createSelector(userFeatureSelector, selectEntities);

export const selectUserById = createSelector(
    selectUserEntities,
    (entities, props) => entities[props.id]
);

On subscribing it returns undefined and does not emit when the reducer updates after the network call is over , i have verified by selecting the entities that the reducer is updating it correctly i get the loaded user object.
I am aware that it has to do with my selector , it does not fire again when the store updates.
Its just what i am thinking , let me know if there are other things which are wrong

dev-ster
@dev-ster
I need to test the next() method of a subject in an ngrx effect.
the test throws an error that toHaveBeenCalled() hasn’t been called
it('should return the logoutSuccess action and cancel the auto logout.', fakeAsync(() => {
      const cancelAutoLogout$Spy = spyOn(effects.cancelAutoLogout$, 'next');

      actions$ = hot('-a', { a: UserActions.logout() });

      flush()
      const expected = cold('-a', { a: UserActions.logoutSuccess() });
      expect(effects.logout$).toBeObservable(expected);
      expect(cancelAutoLogout$Spy).toHaveBeenCalled();
    }));
That’s the effect
@Effect()
  logout$ = this.actions$.pipe(
    ofType(UserActions.logout),
    map(_ => {
      this.cancelAutoLogout$.next()
      return UserActions.logoutSuccess();
    })
  );
Carlos Esteban Lopez Jaramillo
@luchillo17
Hi there, do you guys know a way to use same store in Ngrx and Ngxs? we're starting a migration to Ngrx but want to do it bit by bit, can't find a way to use same redux instance for both.
matrixbot
@matrixbot
@this-is-me:matrix.org Why not just use two stores in parallel?
@this-is-me:matrix.org Why are you migrating to ngrx? Usually I know it the way around :D
Carlos Esteban Lopez Jaramillo
@luchillo17
It's troublesome to deal with circular deps between actions, also the devtools doesn't function all that well, sometimes the diff of the action shows in the next action, the commit action doesn't work with Ngxs and not sure if the jump/skip function does anything
And the biggest thing is the system was made by someone else 2 years ago, it's all jumbled and most of the team knows Ngrx better, so we discussed the swap since the old architecture was already bad.
maxeber
@maxeber
image.png
Hi guys! I am having a lot of trouble trying to split my main reducer into different files, just to better organize my stuff:
So what I tried to achieve is mainly to extract some on(..) from the LeaderboardReducer to some other files like LeaderboardActivityReducer. Somehow I can't find the right ay to do it. Does anyone have a solution for this?
Derek
@derekkite
This is a feature right? If you create a feature state where your break down the feature into smaller sections you can have multiple reducers, one for each specific section.
https://ngrx.io/api/store/ActionReducerMap this is an object with {proportyname: reducer} , and your state corresponds with the same properties.
hellraisercenobit
@hellraisercenobit
hello i have some troubles with router-store, with buildOptimizer enabled featureSelector using selectRouteParams produce error like unexpected undefined value should be function or string... on v9.2 somebody have an idea? ^^
Jack
@jackmercy
Hello guys,
I just started to use @ngrx/entity and I ran to a problem that I can not add new Item to the beginning of the entity by using addOne() function.
Is there any other solution for me?
Derek
@derekkite
@jackmercy cannot meaning what? What is the error?
HMAIDI Thamer
@hmaidithamer
Hello All,
please how to listen and get the result of distapsh action on my effects
matrixbot
@matrixbot
Andreas Weinzierl by selecting from the state of the store?
HMAIDI Thamer
@hmaidithamer
i have a dynamic action this.processStore.dispatch(action); and i need to wait and get the result of my action
?
Derek
@derekkite

@hmaidithamer First, try to work around it.
second, dispatch(myaction(data, tag), then in the effect

createAction((() =>
  this.actions$.pipe(
    ofType(myaction),
    mergeMap(action => myapicall(action.data).pipe(
         map(response => myresponseaction({response: response, tag: action.tag}),
         //error handle
)))

then in the selector, watch for the tag with a parameterized selector https://timdeschryver.dev/blog/parameterized-selectors, where the tag is the parameter, and the selector will fire when it sees the tag in the state.

My preference is to try to figure out a way that it isn't needed. If you have an entity with the tag or id as key, before you start make sure it is clear, then select on that id or key and the data will be what you want.

HMAIDI Thamer
@hmaidithamer
@derekkite First thanks
@derekkite Second Thanks
Marko Stanimirović
@markostanimirovic

Hi everyone! I just released NgRx Handlers - A plugin for boilerplate elimination. I would appreciate if you check it out and let me know what you think :)

https://github.com/markostanimirovic/ngrx-handlers

Jack
@jackmercy
@derekkite The addOne() function of entity adapter only add the new item to the end of list e.g: [2, 3, 4] => [2, 3 , 4, 5]
I want to add an item to the beginning of list like [2, 3, 4] => [5, 2, 3 , 4]
Neeraj Jain
@jainneeraj7483_gitlab
Hello Everyone, I am new to NGRX and having some trouble with feature modules, I have a feature module lazily loaded on a route, and as soon as the lazy module gets loaded it triggers @ngrx/store/update-reducers action and it causes all selector to get fired even when there is no change in the slice of state those selectors are watching.
Derek
@derekkite
@jainneeraj7483_gitlab that action does nothing unless a reducer responds to it. What reducer response, and how?
Neeraj Jain
@jainneeraj7483_gitlab

@derekkite Thank you for responding, I have 2 Modules in my main angular app they both have states and registering as
PeripheralCommLayerModule

@NgModule({
  declarations: [PeripheralCommLayerComponent],
  imports: [
    StoreModule.forFeature(peripheralIntegrationFeatureKey, peripheralReducer)
  ],
  exports: [PeripheralCommLayerComponent]
})
export class PeripheralCommLayerModule {
  static forRoot(environment): ModuleWithProviders<PeripheralCommLayerModule> {
    return {
      ngModule: PeripheralCommLayerModule
      , providers: [{ provide: ENVIRONMENT, useValue: environment }]
    };
  }
}

FuseDeviceTesterModule

@NgModule({
  imports: [
    EffectsModule.forFeature([DeviceTesterEffect]),
    StoreModule.forFeature(fuseDeviceTesterFeatureKey, fuseDeviceReducer),
  ],
  declarations: [
    FuseDeviceTesterComponent,
  ],
  exports: [FuseDeviceTesterComponent],
  schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
export class FuseDeviceTesterModule {
  static forRoot(environment): ModuleWithProviders<FuseDeviceTesterModule> {
    return {
      ngModule: FuseDeviceTesterModule,
      providers: [{ provide: ENVIRONMENT, useValue: environment }]
    };
  }
}

I am importing PeripheralCommLayerModule in my app.module.ts

@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    PeripheralCommLayerModule.forRoot(environment),
    EffectsModule.forRoot([]),
    StoreModule.forRoot({}, { metaReducers }),
    // !environment.production ? StoreDevtoolsModule.instrument({ maxAge: 25 }) : []
  ],
  schemas: [CUSTOM_ELEMENTS_SCHEMA],
  bootstrap: [AppComponent]
})
export class AppModule { }

And FuseDeviceTesterModule is a lazy-loaded module, which is loaded when I route to a particular URL.

When FuseDeviceTesterModule is is firing @ngrx/store/update-reducers action which is received by PeripheralCommLayerModule's reducer and after it selector of PeripheralCommLayerModule is getting fired.

Reducer of PeripheralCommLayerModule :

export const peripheralIntegrationFeatureKey = 'peripheralIntegrationState';

export interface PeripheralIntegrationState {
  peripheralServerInstanceInfo: PeripheralServerInstanceInfo;
}

export const initialState: PeripheralIntegrationState = {
  peripheralServerInstanceInfo: {
    peripheralServerIP: 'localhost',
    peripheralServerPort: 47017
  },
};

const peripheralIntegrationReducer = createReducer(
  initialState,
  on(UpdatePeripheralServerPortAndIP, (state, payload) => ({
    ...state,
    peripheralServerInstanceInfo: payload.peripheralServerInstanceInfo
  })),
);

export function peripheralReducer(state: PeripheralIntegrationState, action: Action): PeripheralIntegrationState {
  return peripheralIntegrationReducer(state, action);
}
Derek
@derekkite
So the PeripheraCommLayer module reducer watches for the init action. What does it do?
Derek
@derekkite
Typically i dispatch initialization actions in the component constructor.
Neeraj Jain
@jainneeraj7483_gitlab
@derekkite it updates the state if the dispatched action matches the one in on method or returns current state as a default case, my problem here is when fusedeviceTesterModules get loaded it dispatch`@ngrx/store/update-reducersand somehow it is triggering the selector i have onperipheralServerInstanceInfo` , i am not able to understand why the selector is triggering if their is no change in my state.
Derek
@derekkite
@jainneeraj7483_gitlab the memoization is a===b which compares object instances.
Neeraj Jain
@jainneeraj7483_gitlab

@derekkite, Thanks for guiding me in the right direction, and yes that is what causing the problem, I have both my states(of both modules) synced with localStorage, and when fusedeviceTesterModules is loaded it updates the localStorage by dispatching @ngrx/store/update-reducer and my local-storage is updating store of PeripheraCommLayer module (somehow it is not able to identify the store has same data that is in the localStorage :-( ) and as the store is updated my selector again is not able to identify that store has same data (as my selector is slicing the store on an object and because of store immutability principle(or recommendation) a===breference check is not able to determine that deeply the object still contains same data as store now has a new object).

I have written an IsEqual function and now I am using createSelectorFactory instead of createSelector and passing it custom memoization function:

const isEqualFunc = (last: any, current: any) => {
  let flag: boolean = last && current || last === current;
  if (last && current) {
    const prevProps: string[] = Object.keys(last);
    const nextProps: string[] = Object.keys(current);
    flag = prevProps.length === nextProps.length;
    if (flag) {
      for (let i = 0; i < prevProps.length; i++) {
        if (typeof last[prevProps[i]] === 'object') {
          if (!isEqualFunc(last[prevProps[i]], current[prevProps[i]])) {
            flag = false;
            break;
          }
        }
        else {
          if (last[prevProps[i]] !== current[prevProps[i]]) {
            flag = false;
            break;
          }
        }
      }
    }
  }
  return flag;
};

const customMemoize = (projectFunc) => resultMemoize(projectFunc, isEqualFunc);

export const getSomeInstance: MemoizedSelector<object, SomeInstance> = createSelectorFactory(customMemoize)(
  selectFeatureStoreSlice,
  state => state.someInstance
);

it's now working fine.

Can someone please verify and tell me if I am handling the scenario correctly, Thanks in advance :-)

Derek
@derekkite
I'd suggest using actions that you define for initialization of each feature. @jainneeraj7483_gitlab
Neeraj Jain
@jainneeraj7483_gitlab
@derekkite pardon me but I am not able to understand what are you suggesting, can u please elaborate a little.
Fahad Kheratkar
@fahadbraveknight
How to use ngrx between multiple tabs
without using localstorage
is there support for indexed db?
MikeOne
@MikeOne
@fahadbraveknight - not out of the box.
apcs.guide
@ApcsGuide_twitter
Is there a way I can call a selector without knowing the actual function until runtime? for example: @Input() selectorName: string; this.store.selector(selectorName)
matrixbot
@matrixbot
Andreas Weinzierl yes, but you need to get to know the selector at runtime, e.g. have a map of seceltors associated to names