Home > Mobile >  How to differentiate loaders in store?
How to differentiate loaders in store?

Time:11-14

I have a loader component:

// loader.component.ts

export class LoaderComponent implements OnInit {
  loader$: Observable<Loader>

  constructor(private store: Store<AppState>) {
    this.loader$ = this.store.pipe(select(selectLoader))
  }

  ngOnInit(): void {
  }

}
// loader.component.html
<p [hidden]='!(loader$ | async)'>loader!</p>

And the store implementation is like this:

// loader-state.actions.ts

export const setLoader = createAction(
  '[Loader] Set loader',
  (loader: Loader) => ({ loader })
)
// loader-state.redcure.ts

const initialState: Readonly<Loader> = false

export const loaderReducer = createReducer(
  initialState,
  on(LoaderActions.setLoader, (state, { loader }) => loader),
)

// loader-state.selector.ts

export const selectLoader = createSelector(
  (state: AppState) => state.loader,
  (loader: Loader) => loader
);

I want to use the loader in different components but the state is global. So if I have multiple instance of the loader component in my application and I set it to true in 1 component, all the loaders will be set to true.

How can I differentiate between different component instances?

CodePudding user response:

Found a solution, but I'm not sure if it's the best.

I added a Input in my loader component:

// loader.component.ts

export class LoaderComponent implements OnInit {
  @Input() parentComponent?: string;

  loading?: boolean

  constructor(private store: Store<AppState>) {
    this.store.pipe(select(selectLoader)).subscribe((loader) => {
      this.loading = loader.loading && loader.parentComponent === this.parentComponent
    })
  }

  ngOnInit(): void {
  }

}

Now I can pass a string from the parent component, and I've updated my store dispatches to include a string:

this.store.dispatch(setLoader({loading: true, parentComponent: 'uploadFile'}))

So now when a component dispatches a loader state it will also add a string (name of the parent component) and that will be checked in the loader component to show the correct loader instance.

CodePudding user response:

Instead of having one loading property, I think it would be better to have a loading status per reducer, or even per entity. That way, you can track each status individually.

  • Related