What is the most effective way to use a withLatestFrom within an effect when integrating a selector with props (MemoizedSelectorWithProps) sourced from the action?

I am struggling to utilize a selector with props (of type MemoizedSelectorWithProps) in an effect inside WithLatestFrom. The issue arises because the parameter for the selector (the props) is derived from the action payload, making it difficult for withLatestFrom to access the action payload.

My current setup involves Angular 7 and ngrx7. I have attempted using a map to create a new observable without much success...

To better illustrate my predicament, here are some simplified code snippets:

Action:

export const GET_INVENTORY = '[App] Get Inventory';

export class GetInventory implements Action {
  readonly type = GET_INVENTORY;
  constructor(public branchId: number) {} 
}

Effect:

@Effect()
getInventory$ = this.actions$.pipe(
  ofType(GET_INVENTORY),
  withLatestFrom(this.store$.pipe(select(getIsStoreInventoryLoaded, {branchId: action.branchId}))), // Unable to access 'action' here
  switchMap([action, loaded]: [GetInventory, boolean] => {
  if (loaded) {
    console.log('already loaded inventory for this branch', action.branchId);
  } else {
    console.log('never loaded inventory for this branch', action.branchId);
  }
});

While this represents a simplified version of my scenario, the fundamental concept mirrors what I am dealing with in my actual project - maintaining inventory data per "branch" within the store. As a chain of supermarkets, each branch has its own specific inventory data page, where re-fetching should be avoided if already loaded. If you have alternative suggestions other than utilizing MemoizedSelectorWithProps, I am open to exploring those as well.

Answer №1

To solve this issue, consider using either a switchMap or a mergeMap along with a combineLatest.

Here's an example:

@Effect()
getInventory$ = this.actions$.pipe(
  ofType(GET_INVENTORY),
  mergeMap(action =>
    combineLatest(
      of(action),
      this.store$.pipe(select(getIsStoreInventoryLoaded, {branchId: action.branchId}))
    )
  ),
  tap(([action, loaded]) => {
    // Implement the remaining portion of your code here...
  })
)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to retrieve a variable that has been exported from a page and access it in _

Suppose this is my pages/visitor.tsx const PageQuery = 'my query'; const Visitor = () => { return <div>Hello, World!</div>; }; export default Visitor; How can I retrieve PageQuery in _app.tsx? One approach seems to be by assi ...

Guide to invoking a server-side function through JSON data?

Here is the code I am working on: <script type="text/JavaScript> var myarray = new array(); function getsvg1() { $.ajax({ alert("hello"); type: "post", url: "WebForm1.aspx/getsvg1", ...

What is the best way to merge two similar arrays of objects into one array object?

Apologies in advance if this question has been asked previously, I'm struggling with how to phrase it. Essentially, the API I'm using is returning an array of similar objects: const response.survey = [ { 1: { id: 1, user: user_1, points: 5 ...

What is the best way to eliminate square brackets from keys within an array of objects in TypeScript?

I am currently working on a task to eliminate all square brackets from the keys in the entries field within an array of objects: data: [ {title: "Title1", entries: { 'Entry1': 333333, '[ABC]Entry2': 1234, 'Entry3' ...

React: When state is updated and a console.log is used, the console displays the previous state instead of the updated

Upon clicking the button, a peculiar sequence unfolds - the console displays 0 and the page refreshes to show 1 function App() { const [count, setCount] = useState(0); const addOne = () => { setCount(count + 1) console.log(count) } ...

Verifying a checkbox selection within an Autocomplete feature using MUI

[ { label: 'First', checked: false }, { label: 'Second', checked: true } ] Here is a brief example of how the data may be structured. I am utilizing Material UI's Autocomplete feature to enable searching based on labels. Thes ...

In order to incorporate Bootstrap with Angular2, I had to execute a specific command

For incorporating bootstrap with angular2, I executed the following command: $ npm install --save @ng-bootstrap/ng-bootstrap The output displayed: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="40212e27352c2132726d313529232 ...

Can the individual headers of an ag-grid column be accessed in order to apply an on-mouseover event with a specific method?

In my current project, I am utilizing ag-grid to create a dynamic web-application that combines tools from various Excel files into one cohesive platform. One of the Excel features I am currently working on involves displaying a description when hovering ...

Utilizing React Hooks and Firebase Firestore onSnapshot: A guide to implementing a firestore listener effectively in a React application

SITUATION Picture a scenario where you have a screen with a database listener established within a useEffect hook. The main goal of this listener is to update a counter on your screen based on changes in the database: (Utilizing the useEffect hook without ...

Passing NextJS props as undefined can lead to unexpected behavior and

Struggling with dynamically passing props to output different photo galleries on various pages. One of the three props works fine, while the others are undefined and trigger a warning about an array with more than one element being passed to a title elemen ...

React Project Encounters NPM Installation Failure

I recently started delving into the world of React and experimenting with different examples. Everything was running smoothly until I attempted to start the server [npm start] and encountered an error as shown below. Despite my best efforts, I can't p ...

Mixing TypeScript generic types loosely

Let's explore a simple example of typescript mixins: import { Observable, of } from 'rxjs'; class Service<TDataType> { public foo(f: TDataType): Observable<TDataType> { return of(f); } } type GConstructor<T = {}> = new ...

What are the methods for showcasing data within a string?

I'm struggling to figure out how to display the column names from a JSON file. Currently, all the column names are being displayed in one column, and empty fields are showing up for some reason. How can I format it so that the column names are listed ...

Using the 'client-side rendering' and runtime environment variables in Next.js with the App Router

In the documentation for next.js, it's mentioned that runtime environment variables can be utilized on dynamically rendered pages. The test scenario being discussed involves a Next.js 14 project with an app router. On the page below, the environment ...

Display the changing value at the beginning of the drop-down menu

I'm currently working on an AngularJS forEach loop where I need to display a dropdown list with dynamic values. The goal is to have the value stored in $scope.showCurrentProgram as the first selected element in the dropdown list when the page loads, a ...

There were no visible outputs displayed within the table's tbody section

import React from 'react'; export default class HelloWorld extends React.Component { public render(): JSX.Element { let elements = [{"id":1,"isActive":true,"object":"Communication","previ ...

Immersive Visual Symphony through Dynamic Multi-Layered

My goal is to create captivating animations for my multiple background images. Here's the CSS code I've come up with: .header { background-image: url('/img/cloud2.png'), url('/img/cloud3.png'), url('/img/cloud1.png&apos ...

Issue with displaying decimal places in Nivo HeatMap

While utilizing Nivo HeatMap, I have observed that the y value always requires a number. Even if I attempt to include decimal places (.00), it will still trim the trailing zeros and display the value without them. The expected format of the data is as foll ...

When attempting to compile the building project following the upgrade to Angular 9, an error message is displayed stating "Unable to access property 'length' as it is undefined

I'm currently in the process of updating my Angular 9 project by following the migration guide on update.angular.io. After running ng update @angular/core @angular/cli, I encountered an error "ERROR in Cannot read property 'length' of undefi ...

Troubleshooting Issue: ASP.NET UpdatePanel Not Responding to jQuery

I am having difficulties invoking jQuery functions within an "asp:UpdatePanel". Despite the code provided below, my attempts to add a class to the div element ".popup-body" are unsuccessful. Interestingly, the "alert();" function works without any issues. ...