Search code examples
spartacus-storefront

How to eaisly pass dynamic parameter to a Query (QueryService) in Spartacus?


At the first sight the Query (QueryService) in Spartacus doesn't seem to accept any dynamic parameters. For instance fetching list of Orders but based on the dynamic parameter searchPhrase$. The workaround is to configure a reloadOn event for the Query.


Solution

  • You can use dynamic parameters in Spartacus Query (QueryService). It suffices to use RxJs swtichMap for example and switch from your dynamic parameter searchPhrase$ to the call to the data service (connector). For example:

    export class CustomOrdersService {
      /* ... */
      protected queryService = inject(QueryService);
      protected searchPhrase$ = new BehaviorSubject<string>('');
    
      protected ordersQuery$: Query<Orders[]> = this.queryService.create(() =>
        this.searchPhrase$.pipe(
          switchMap((searchPhrase) => {
            this.connector.getOrders({ searchPhrase }); // loads actual Orders from http
          })
        )
      );
    
      public setSearchPhrase(searchPhrase: string): void {
        this.searchPhrase$.next(searchPhrase);
      }
      public orders$ = this.ordersQuery$.get();
    }