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
);