Setting the initial state for your ngrx store application is a crucial step in ensuring the

I'm completely new to ngrx and I'm currently exploring how to handle state management with it. In my application, each staff member (agent) is associated with a group of customers. I'm struggling to define the initial state for each agent object.

import { createReducer } from "@ngrx/store";
import { Cursor } from "../../../models/cursor";
import { Customer } from "../../../models/customer";

export interface State {
  agent_customer: {
    [agentId: number]: {
      customer: Customer[];
      cursors: Cursor;
      total: number;
      loading: boolean;
      errorMessage: string;
      items_per_page: number;
      pageSizeOptions: number[];
      pageIndex: number;
      searchKey: string;
    };
  };
}

It's important that each agent object has an initial state set up.

For example:

export const initialState: State = {
  agent_customer: {
    1: {
      customer: [],
      cursors: {
        after: "",
        before: "",
        hasNext: false,
        hasPrevious: false,
      },
      total: 0,
      loading: false,
      errorMessage: null,
      items_per_page: 2,
      pageSizeOptions: [2, 3, 5, 10, 15],
      pageIndex: 0,
      searchKey: "",
    },
  },
};

Edit: This is a representation of what the store should look like if everything goes smoothly.

agent_customer: {
    198282: {
      customer: [],
      cursors: {
        after: "",
        before: "",
        hasNext: false,
        hasPrevious: false,
      },
      total: 0,
      loading: false,
      errorMessage: null,
      items_per_page: 2,
      pageSizeOptions: [2, 3, 5, 10, 15],
      pageIndex: 0,
      searchKey: "",
    },
    165436: {
      customer: [],
      cursors: {
        after: "",
        before: "",
        hasNext: false,
        hasPrevious: false,
      },
      total: 0,
      loading: false,
      errorMessage: null,
      items_per_page: 2,
      pageSizeOptions: [2, 3, 5, 10, 15],
      pageIndex: 0,
      searchKey: "",
    },
    981342: {
      customer: [],
      cursors: {
        after: "",
        before: "",
        hasNext: false,
        hasPrevious: false,
      },
      total: 0,
      loading: false,
      errorMessage: null,
      items_per_page: 2,
      pageSizeOptions: [2, 3, 5, 10, 15],
      pageIndex: 0,
      searchKey: "",
    },
  },

What I aim to achieve is to successfully establish the initial state for each subsequent object added to the store.

Answer №1

Utilizing the Store Module is recommended in this scenario.

import {createAction, props} from '@ngrx/store'

For more information, consult the official guide-

We also suggest reviewing this gist - https://github.com/ngrx/platform/issues/662

Answer №2

To ensure proper typing, be sure to define the entity type and set the initial state for your reducer.

import { Action, createFeatureSelector, createReducer, on } from '@ngrx/store';
import { ACTION } from './actions';
import { Entity} from './entity';

export interface CustomState {
   agent: Entity[] // Define the entity type as Entity[]
}

// Initialize the state with your defined interface
const initialState: CustomState = {
    agent: [
     // Assign each object with type Entity
     {
       total: 0,
       loading: false,
       errorMessage: null,
       items_per_page: 2,
       ...
     }
]
}

const reducer = createReducer(
    initialState,
    on(ACTION, (state, { payload }) => ({ ...state, agent: payload }))
);

export function customReducer(state: CustomState, action: Action) {
    return reducer(state, action)
};

export const getCustomState = createFeatureSelector<CustomState>('customName');

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

"Observables in RxJs: Climbing the Stairs of

Previously, I utilized Promise with async/await syntax in my Typescript code like this: const fooData = await AsyncFooData(); const barData = await AsyncBarData(); ... perform actions using fooData and barData However, when using RxJs Observable<T> ...

Utilize a dynamic approach to add the active class to navigation list items

My files all have a header that includes a navigation bar. I am trying to use jQuery to add the 'active' class to the relevant list items (li). The method I initially thought of involved setting a variable on each page, assigning an ID equal to ...

Error encountered while sending a post request from Angular to NodeJS with JSON data

When making a POST request to a NodeJS app from Angular, the request code in Angular is as follows: export class SearchComponent { constructor(private http: HttpClient) {} newWord = ''; keyword = ''; onClick() { const head ...

Avoid using the <app-componentName> tag when displaying content in an Angular application

Is there a way to exclude the <app-componentName> tag from being generated in Angular HTML output? Let me illustrate what I mean using an example: Imagine I have a chat-box with a message component structured like this: <div class="chatbox&q ...

What is the process of initializing divs in DataTables?

My application has a DataTable installed, but I encountered an error message stating "DataTables warning: Non-table node initialisation (DIV). For more details about this error, please visit http://datatables.net/tn/2". I'm aware that DataTables is d ...

Revamping outdated dependencies in package.json for Angular 6

Currently, I am working with the latest version of Angular (6) and have been attempting to update my dependencies in the package.json. I was wondering if it is safe to use the npm update command to update all dependencies, or if there are other methods th ...

Utilizing an external API in Javascript for fetching data

Is it permissible for me to directly initiate an API request from JavaScript to an external API (in this scenario at ) using the XMLHttpRequest object? If not, what steps should I take to retrieve data from this source? Do I need to incorporate a PHP bac ...

AngularJS Error: $element.find(...) does not support iteration

I'm attempting to utilize a datatable in my AngularJS application. Below is the HTML code I've implemented: <div ng-app="datatable"> <div ng-controller="voucherlistcontroller"> ...

Get the date string formatted for an Angular2 date range picker

In my Angular2/Spring web application, I am utilizing a calendar from the following sources: https://www.npmjs.com/package/ng2-daterangepicker http : // www. daterangepicker . com/ The issue I am encountering is with formatting the date output. Accordin ...

Blur images on parent div when hovering using javascript

After some extensive searching, I came across a few helpful explanations on how to achieve my desired outcome. By combining them, I was able to get everything working smoothly with the hover effect over the image itself. However, when I attempted to trigge ...

AngularJS 1.7.x's ngRoute tabs navigation post authentication

In my current project, I am using ngRoute to route users to the login page and upon successful login, they should land on the dashboard page. However, I am facing a problem with the dashboard page where I need to have two or more tabs that render HTML pag ...

What is the correct method for downloading an Excel file in a Vue.js application?

I am having difficulty downloading an Excel file in xlsx format using my Vue.js application. The Vue.js application sends a post request to the Node.js application which then downloads the Excel file from a remote SFTP server. The backend application is fu ...

Height and placeholder issue with ion-searchbar

Hey there, I hope everything is going well for you. I've encountered a problem with the Ionic 5 - Angular Searchbar feature. This is how I added the searchbar: <ion-searchbar [(ngModel)]="text" (ionChange)="sear ...

Is it possible to trigger multiple button clicks using JQuery simultaneously?

Hello everyone, I am new to StackOverflow and this is my first question here. I hope it's not too silly. Thank you in advance for your help! I am trying to achieve a functionality where one button click triggers the clicks of multiple other buttons u ...

What is the best way to save longitude and latitude coordinates in a database using the <input> method?

Learn how to use HTML code <html> <body> <p>Press the button below to receive your coordinates.</p> <button onclick="getLocation()">Get Coordinates</button> <p id="demo"></p> <script> var x = doc ...

Unable to establish proper functionality of username variables in Node.js chat application

For my latest project, I am developing a chat application in node.js following a tutorial from socket.io. The main objective of the app is to allow users to input their username along with a message, which will then be displayed as "username: message" in t ...

Getting the value from a .sh (Shell Script) file in React: How to do it?

There is a .sh file that contains the following code: echo "Hello" This code produces the output: Hello The question at hand is: I am trying to extract the output from the .sh file and integrate it into my React application. After exploring various ...

Is there a way to verify the selected navigation item in the console?

Need help with checking the selected navigation using console.log? export const navItems: NavData[] = [ { name: 'Book #1', url: '/book', icon: 'fa fa-book', children: [{ name: 'Book #2', ...

Tips for incorporating the "build" directory into the Travis-CI build process and deployment of an npm module

Currently, I am working with a Typescript module that has a directory ./src And I also have travis-ci set up for the project. language: node_js node_js: - 5.1.0 install: - npm install - npm install -g mocha - npm install -g gulp - npm install -g tsd - ...

The animation using Jquery and CSS is experiencing some glitches on Safari when viewed on an

Why is smooth animation not working on iPad Safari with jQuery animate? $('#myId').css({ 'left': '-100%' }).animate({ 'left': '0' }, 300, 'linear'); I also tried using the addClass option and in ...