retrieve asynchronous data from the server using ngrx

How can I retrieve asynchronous data from the server?

I am looking to save this data in a global store for future updates.

I'm having trouble grasping the concept of asynchronous calls, such as in Redux.

While I was able to understand it with simple data, retrieving data from the server is proving difficult for me.

I would greatly appreciate any assistance.

app.components.ts:

   import { Component } from '@angular/core';
import { Store } from '@ngrx/store';
import { dataSelector, DATA_LOAD } from './store.service/ngrx.store/globalStore.action';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})

export class AppComponent {
  
  data$ = this.store.select(dataSelector)

  constructor(private store: Store) {

    this.store.dispatch(DATA_LOAD());

  }

reducer.reducer.ts:

import { ActionReducerMap, MetaReducer } from '@ngrx/store';
import { environment } from 'src/environments/environment';

import { counterReducer, DATA_KEY } from './globalStore.action';


export interface State {
  [DATA_KEY]: any;
}

export const reducers: ActionReducerMap<State> = {
  [DATA_KEY]: counterReducer,
};


export const metaReducers: MetaReducer<State>[] = !environment.production ? [] : [];

action.action.ts:

import { createAction, createFeatureSelector, createReducer, createSelector, on, props } from '@ngrx/store';

export const DATA_KEY = 'DATA';

export const DATA_LOAD = createAction('[DATA] DATA_LOAD');


export const initialState: any = {
  data: {}
};

export const counterReducer = createReducer(
  initialState,
  on(DATA_LOAD, state => ({
    ...state.data,
    ...fetch('https://gutendex.com/books')
        .then(response => response.json())
        .then(data => data)
  }))
);

export const featureSelector = createFeatureSelector<any>(DATA_KEY);

export const dataSelector = createSelector(
  featureSelector,
  state => state.data
);

Answer №1

Reducers should only be used for pure and synchronous methods. Any side effects, such as API calls, should be handled in @ngrx/effects. The typical workflow is as follows:

  • A component dispatches a FETCH action
  • An effect picks up the FETCH action, makes the API call, and then dispatches either a FETCH SUCCESS or FETCH ERROR action
  • The reducers respond to the FETCH SUCCESS action by updating the state
  • Selectors are updated and the component receives the data

For an example, refer to the sample app in the ngrx documentation.

Additional resources:

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

The error message "Property 'map' is not found on type 'User' in React with typescript"

I am currently experimenting with React using TypeScript. I have set up useState with an object but I am encountering issues trying to use the map function with that object. Below is the error message I am facing: Property 'map' does not exist ...

Show the hash codes in angular2

I need assistance with displaying hash values in angular2. The response I am receiving is in the following format: [{"1":"7"},{"2":"6"},{"3":"8"},{"4":"1"}] The key "1" represents user_id and the value "7" represents the count of posts for that user. I w ...

Enumerated type alias in Typescript

Within my typings file, I have the following: declare namespace Somatic { enum PropType { html, object, css } } In a separate file named index.ts, I create a shorter alias for this enum like so: type PropType = Somatic.Pr ...

An effective method for excluding null values with an Angular pipe

I am currently working on an Angular pipe that filters results based on user input. The problem I'm encountering is that some of the results do not have a value, resulting in this error message: Cannot read property 'toLocaleLowerCase' o ...

How to update an Angular 2 component using a shared service

My question is regarding updating components in Angular 4. The layout of my page is as follows: Product Component Product Filter Component Product List Component I am looking to link the Product Filter and Product List components so that when a user c ...

I'm working on an Angular2 project and I'm looking for a way to concatenate all my JavaScript files that were created from TypeScript in Gulp and then include them in my index

How can I concatenate all JavaScript files generated from typescript in my Angular2 project with Gulp, and then add them to my index.html file? I am using Angular2, typescript, and gulp, but currently, I am not concatenating the javascript files it genera ...

Modifying Angular 4 instance field in the code does not update the template as expected

One issue I am encountering is that changes in the instance variable in my component class are not automatically reflected in my template file unless I explicitly call ref.detectChanges The method signInWithGoogle in my auth service is called from the com ...

Conduct surveillance on the service function call within the constructor

I am currently facing a challenge with trying to monitor a service function call that is executed in the constructor. The test is straightforward, simply aiming to confirm that the function call is indeed made. beforeEach(async(() => { TestBed.con ...

Angular 6 - Share content easily on mobile devices (IOS, Android)

After reviewing this example detailing the use of Angular 5 for copying to clipboard, I encountered issues when trying to run it on the iPhone 6s. Is there a more comprehensive solution available? ...

React-snap causing trouble with Firebase

I'm having trouble loading items from firebase on my homepage and I keep running into an error. Does anyone have any advice on how to fix this? I've been following the instructions on https://github.com/stereobooster/react-snap and here is how ...

Exploring Nested <Routes> with ReactJs

My decision on whether to display the Foo page or the Bar page is based on the route. However, the Foo page itself contains two sub-routes for components to render depending on the URL path - such as FooOne or FooTwo. This results in having two layers of r ...

How can I retrieve the name of a constant enum member in TypeScript as a string?

Consider the following const enum declaration: const enum Snack { Apple = 0, Banana = 1, Orange = 2, Other = 3 } Is it possible in TypeScript to retrieve the string representation of a specific member? In C#, this could be achieved with ...

Acquire data from promise using an intermediary service in Angular 5

I'm facing an issue with retrieving promise data through an intermediate service. The setup involves a component, an intermediate service, and an HTTP service. My component makes a call to the intermediate service, which then forwards the request to ...

The absence of the import no longer causes the build to fail

Recently, after an update to the yup dependency in my create react-app project, I noticed that it stopped launching errors for invalid imports. Previously, I would receive the error "module filename has no exported member X" when running react-scripts buil ...

Angular service is able to return an Observable after using the .then method

I am currently facing an issue with retrieving the authentication status in a service method. Everything seems to be working fine except for the return statement. I am struggling with the usage of .then inside .map and I am unable to figure out how to retu ...

What method is most effective for duplicating objects in Angular 2?

Is it just me, or does Angular 1.x have methods on the global angular object like angular.copy and angular.shallowCopy that are missing in Angular 2? It seems like there is no equivalent version in Angular 2 documentation. If Angular 2 doesn't plan on ...

Ways to modify the access control to permit origin on a specific API URL in React

https://i.stack.imgur.com/tqQwO.png Is there a way to modify the access control allow origin for a URL API? I keep encountering error 500 whenever I try to load the page. After logging in, I included this code snippet: const options = { header ...

The application was not functioning properly due to an issue with the getSelectors() function while utilizing @ngrx/entity to

Currently, I am facing an issue with implementing a NgRx store using @ngrx/entity library. Despite Redux Devtools showing my collection loaded by Effect() as entities properly, I am unable to retrieve any data using @ngrx/entity getSelectors. Thus, it seem ...

Leveraging private members in Typescript with Module Augmentation

Recently, I delved into the concept of Module Augmentation in Typescript. My goal was to create a module that could inject a method into an object prototype (specifically a class) from another module upon import. Here is the structure of my folders: . ├ ...

What could be causing issues with my unit tests in relation to Angular Material tooltips?

I have a unique and specific issue with the following unit test code. It is very similar to another working file, but I am encountering an error related to mdTooltip from the Angular Material library. Here's the problematic portion of the code: Phant ...