Implementing a default value for entities in ngrx

Is there a way to establish a default value for entities when initializing state in ngrx entities?

apple.model.ts

export class Apple {
    id: number;
    color: string;
}

apple.reducer.ts

export interface AppleState extends EntityState<Apple> { }

export const appleAdapter: EntityAdapter<Apple> = createEntityAdapter<Apple>();

const applesInitialState: AppleState = appleAdapter.getInitialState();

export const initialState: State = {
    apples: applesInitialState
};

export function reducer(state = initialState, action: AppleActions): State {
    switch (action.type) {
        // ...
    }
}

For instance, if I want to set a default color like 'red'.

Answer №1

If you're looking for a recommendation, I would advise utilizing the default constructor in this scenario:

export class Potato {
    id: number;
    weight: number;

    constructor() {
        weight = 0.2;
    }
}

Answer №2

Avoid adding classes to the storage in order to maintain serializability. Although your potato may be tempting to equip with functions while it exists, such additions can lead to complications.

Consider utilizing a factory function for creating instances of Potato instead.

interface Potato {
  id: number;
  weight: number;
}

const createPotato = (potato: Potato = { id: undefined, weight: 0.2 }) => potato;

console.log(createPotato());
console.log(createPotato({id: 20, weight: 300}));

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

Break down and extract elements using typedEvent in TypeScript

Within the external library, there is the following structure: export interface Event extends Log { args?: Result; } export interface TypedEvent<EventArgs extends Result> extends Event { args: EventArgs; } export type InstallationPreparedEven ...

Issue encountered when utilizing properties in a Vue.js instance with vue-class-components and TypeScript

I am looking to create a global variable for my server's URL. In my main.ts file, I added the following line: Vue.prototype.$apiUrl = "http://localhost:3000"; Then, when trying to use it in my App.vue file: console.log(this.$apiUrl) The URL is disp ...

"Error: Import statement must be used within a module" encountered in TypeScript (with nodemon) and Node.js (running in Docker)

Within the server directory of my web application written in TypeScript, there is a nodemon command used to automatically restart the code after changes are made. The command looks like this: nodemon dist/index.js However, upon running it, an error is enc ...

Steps to successfully deploy an Angular application using Jenkins

I'm in the process of deploying my Angular application to an AWS EC2 instance. For version control, I'm utilizing Bitbucket and Jenkins for continuous integration. ...

Changing the ngModel value within ngFor loop

I am working on a project where I need to display a list of grades from an object called 'grades'. Additionally, I want to integrate a slider component for each grade, with the value of the slider corresponding to a predefined list. However, it s ...

The animation for the menuItem in the MenuBar in React is not functioning as expected

In my project, I am using React with TypeScript and implementing animations with framer-motion. One issue I am facing is that when the button is pressed to open the menubar, the menuItem should move according to the frame-motion animation but it is not. I ...

Run the Ionic function only when the app is launched for the first time

I'm facing an issue with a function in Ionic storage that sets an array to default values. I only want this function to run the first time the app is launched on a user's phone, but currently it runs every time the app is opened because it's ...

Creating custom generic functions such as IsAny and IsUnknown that are based on a table of type assignability to determine

I attempted to craft a generic called IsAny based on this resource. The IsAny generic appears to be functioning correctly. However, when I implement it within another generic (IsUnknown), it fails: const testIsUnknown2: IsUnknown<any> = true; // iss ...

Troubleshooting a navigation issue in Angular involving the mat-sidenav element of material UI while transitioning between components

I would greatly appreciate your assistance in resolving the issue I am facing. I have been trying to navigate from one view to another, but when I use an <a> tag nested within a <mat-sidenav>, I encounter the following error: "Uncaught (in prom ...

Guide to updating the content of an input field

As a newcomer hobbyist, I'm attempting to automate my web browsing experience. My goal is to have the browser automatically fill in my username and password, and then click the sign-in button using a combination of JavaScript and Tampermonkey. This me ...

Guide to setting a SetState function within a component (Using NextJS and TypeScript)

I'm currently diving into TypeScript, and I've hit a roadblock when it comes to the correct assignment for my setState function that I need to pass to a component. /index.tsx import { Dispatch, SetStateAction, useState } from "react"; ...

Improving efficiency of API requests to a single endpoint utilizing varied payloads

Currently, I am encountering an issue with an API in a significant Angular Project. Utilizing rxjs 6, the API calculates product costs across multiple dates and cities. This particular API is accessed from numerous components, with 3-4 components calling ...

Angular 8: Implementing Form Validation with a Boolean Flag

Within my HTML code, I have a function (change)="limitUser($event)". In Typescript, I utilize a for loop to iterate through each element and determine if the value is less than 10. If it exceeds 10, the inValid = true condition is set. All form fields in m ...

Dynamic background color changes with each click or scroll

I have successfully created a function to Generate Background Colors, but the problem arises when I interact with the page by clicking or scrolling, causing the background colors to change repeatedly. HTML: <ion-button shape="round" color="clear" [ngS ...

What is the best way to utilize v-model with an array of strings in a Vuex store when using v-for

Encountered an issue while trying to set a value in an Array within the Vuex Store: VueCompilerError: v-model cannot be used on v-for or v-slot scope variables because they are not writable. Seeking alternatives to achieve this without creating a local co ...

What is the process for developing an Angular package that contains a collection of reusable pages and routes?

Is it possible to create Angular packages as a comprehensive reusable set of pages? If so, what is the fundamental way/architecture to implement it? Imagine having an Angular app and installing an npm package '@myuilibrary/account'. Suddenly, 11 ...

Discrepancy detected in AGM Map printout

When attempting to print my Angular AGM Map from Chrome, I noticed a large grey gap in the map. This gap is visible even when "background graphics" are turned off and it causes the map image below it to shift downwards. If you want to reproduce this issue ...

Testing the combination of Angular units with combineLatest

Recently, I delved into unit testing using the Jest Framework in Angular. However, I've encountered a roadblock while trying to write unit tests for the combineLatest RxJS operator. Check out my component below: Component: public userData; public pro ...

Receiving an error in Angular 7: Unable to retrieve value from child component as it is returning Undefined

I am looking for a way to transfer a value between components so that I can switch from a list of candidates to another panel where I can edit the selected candidate. Unfortunately, I encountered an error: ERROR TypeError: "this.listCandidateComponent is ...

What is the best way to exhibit information from a lone table column in a modal using Angular 7?

Is there a way to have an "edit" button beside each row in the appointments table that triggers a modal popup allowing users to change appointment dates? Unfortunately, I'm facing an issue where the modal does not pop up and my screen turns white. ** ...