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

Display the data received from the client on the NodeJS server

I have a basic html file that includes the following snippet of javascript: <script type="text/javascript"> $.ajax({ url: 'http://192.168.X.X:8080', data: '{"data": "1"}', dataType: ...

Best practice in Angular 2: The difference between binding an object as a whole versus binding its individual

What is the best approach for a child component when dealing with object properties and change events? Example 1 <parent-component> <child-component [exampleInput]="object.val" (valueChanged)="updateObjectValue($event)"> ...

Tips for updating content (wishlist) without the need to refresh the page

Currently experimenting with the TMDb API to enhance my PHP skills. I've successfully created a wishlist feature and now looking to optimize the script. A function is implemented on each movie page for adding movies to the wishlist. function getButt ...

My current objective is to extract the information from a specific item within a combobox by implementing the following code

alert($("select[name="+this.name+"] option:selected").text()); However, I am not receiving any output unless I explicitly specify the name of the combobox instead of using this.name. This issue may be related to the way quotes are being handled. ...

Tips for eliminating white frames or borders on the Mapbox canvas map

In my current project using Angular 10, I have integrated Mapbox to display path routes. Following the standard Angular practice of splitting components, I separated the map rendering component and called it into the main map component. However, I encounte ...

Strive to discover the ideal solution for capturing a screenshot of an OpenLayers map using html2canvas. Currently, the map elements are losing their CSS classes and images are not

Seeking advice on the best solution for working with html2canvas and css. I'm trying to take a screenshot of a map that includes various elements, but after capturing the image, all the css classes are lost and the images are not rendered properly. S ...

Rotate images with animation using Javascript

Seeking assistance with a swinging motion using two simple functions in Javascript. As a newcomer to the language, I am looking for guidance to achieve my goal. First function: function up() { imgObj.style.left = parseInt(imgObj.style.transform = 'r ...

Unable to locate the internal/fs module, current solutions are proving ineffective

Every time I try to run my project, I encounter the same issue despite downgrading my node version to 8.4.0 (npm version 5.3.0). I have tried various solutions such as removing the node_modules, running npm cache clean --force, and then npm install, but no ...

Issues with triggering the success block in AngularJS and Node.js Express when using $http.get

As a beginner in the world of AngularJS and Node.js, I'm facing an issue with my $http.get method. The problem is that the success callback block does not get executed when the request is successful, whereas the error callback works just fine when the ...

Is there a way to generate a button that displays the subsequent 5 outcomes from the database without navigating away from the current

I am looking to implement a button on my webpage that, once clicked, will load the next set of five questions from my database. I prefer not to use pagination or the GET method to prevent users from navigating back to previously answered questions. My goa ...

customize your selections in p-multiselect with dynamic choices primeng angular 2

I am currently working on implementing the Primeng datatable. I have put together an array containing headers, fields, and options called headersList. Here is how it looks: { header: "Time", field: "time", options: "timeOptions" }, { header: ...

"An error occurred: Attempting to access properties of an undefined object (specifically 'foundTicket'). While the getTickets() function, which fetches data from MongoDB using Mongoose, is working fine, the getTicketById()

I recently started working with next.js and I'm following a project tutorial by a YouTuber. Here is the link to my code: https://github.com/Fanguiee/ticketing-app/tree/edit-existing-item or you can also read below. Thank you in advance :) Screenshot: ...

Creating your own custom operator using observables is a powerful way

const apiData = ajax('/api/data').pipe(map((res: any) => { if (!res.response) { console.log('Error occurred.'); throw new Error('Value expected!'); } return res.response; }), An enhancement is needed to encapsulate the ...

Ways to verify an NPM package for non-JavaScript code

How can we determine if an npm package consists purely of JavaScript without any bindings or dependencies that require compiling? For instance, the node-speaker package (https://github.com/TooTallNate/node-speaker) requires compilation (mpg321), while req ...

Exploring the Contrast between Using @import for Styles and js Import for Webpack Configuration

While delving into the source code of ant-design, I couldn't help but notice that each component has both an index.ts and a index.less file in the style folder. This got me thinking - why is JavaScript being used to manage dependencies here? What woul ...

Is there a way to retrieve the value of an HTML variable using Selenium?

Seeking assistance in determining the progress value of a video using Selenium. I understand that I need to utilize JavaScript executor, but have been unsuccessful in finding a solution so far. The element in question is: <div aria-label="scrub bar" a ...

Using Vuex and array.findIndex but unable to locate a matching element

I am encountering an issue with the array.findIndex method. Despite being certain that there is a match in the array I am searching through, findIndex consistently returns -1. let index = state.bag.findIndex((it) => { it.id === item.id console. ...

Guide on redirecting to a specific tab data target in Symfony 5

When a user is on the 3rd tab and clicks on a DELETE button, I want to redirect the user back to the same 3rd tab on the page. **Template:** <nav> <ul class="nav nav-tabs"> <li class="nav-item"> ...

What is the best way to prevent the body from scrolling when scrolling on a fixed div without making the body's scroll bar disappear?

Is there a way to prevent the body from scrolling while I scroll on a fixed div? I attempted using overflow:hidden for the body, which stops scrolling but causes the page to shake when the scroll bar disappears. Is there a solution that allows me to keep ...

Traversing through each element using Array method

I need to create a redux function that will add a specified number n to the fourth element of an array every time a button is clicked. However, if the element is either L or M, I do not want the addition to occur. For example, starting with this initial a ...