What is the best way to save objects in the store (ngrx, ngxs) while preserving their methods functionality?

As I delve into the Redux pattern, I realize the importance of storing only plain objects in the Store. However, I find myself wanting to use more complex objects with methods like "hasParent", "isReadonly", and "isValid" in my application.

While ngrx allows for storing such objects, it can create a plethora of issues down the line.

So, how should I handle this dilemma of storing complex objects? I have two potential solutions in mind:

A) - Serialize the object into plain data before saving it to the store - Map the plain data back to the object when reading from the store (either using a mapper or manually with an object constructor and setters) B) - Abandon the use of classes/objects entirely and rely solely on plain data - Move the hasParent, isReadonly, isValid methods to helpers/services instead

Unfortunately, neither of these options is without drawbacks. Which approach do you think is the better choice? Are there any other strategies I could consider?

Answer №1

Is it possible to store objects with methods in the ngrx or ngxs store? --> No, objects with functions should not be stored in a state. The state should only contain data and not functions associated with it. (Although you mentioned this in your question details, it's important to reiterate)

Regarding the functions you mentioned:

  • readonly: Instead of using this as a function, consider representing it as a boolean flag within the object itself. If read-only status depends on external factors like user roles, handle it through a utility function separate from the state in order to keep the state minimal.
  • isValid: It's advisable not to store invalid data in the store, which could potentially impact other components. Generally, data in the store should be considered valid unless there are specific use cases that require otherwise.
  • hasParent: This might be better expressed as "parentId", allowing you to retrieve the parent object using a helper method. However, without knowledge of your structure, it's hard to provide a definitive answer.

Before deciding on utilizing a store, consider if it's truly necessary for your requirements. Perhaps a service could suffice instead. Although stores are popular, they're not always essential for every application. Avoid using them simply because they're trending!

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

Creating a DynamoDB table and adding an item using CDK in Typescript

Can anyone guide me on how to add items to a Dynamodb Table using CDK and Typescript? I have figured out the partition/sort keys creation, but I am struggling to find a straightforward solution for adding items or attributes to those items. Additionally, ...

Ways to retrieve and upload a blob from a file object

After receiving a file object via an HTML input on-change event in my component.html: onFileSelected(event) { this.selectedFile = event.target.files[0]; } Now, I need to send a POST request to upload the image to the database. The database only acc ...

An error occurred: The property 'toUpperCase' cannot be read of an undefined Observable in an uncaught TypeError

Encountering an issue during the development of a mobile app using the ionic framework for a movie application. After finding an example on Github, I attempted to integrate certain functions and designs into my project. The problem arises with the 'S ...

Is it possible to enlarge the panel only by clicking on the text, without affecting the entire header panel?

I need help with my accordion setup. I want to be able to expand or collapse each panel by clicking only on the header text, not the entire header area. Can anyone provide guidance on how to achieve this? For example, when I click on the text for 'He ...

Is there a way to create a list of languages spoken using Angular?

I am in search of a solution to create a <select> that contains all the language names from around the world. The challenge is, I need this list to be available in multiple languages as well. Currently, I am working with Angular 8 and ngx-translate, ...

Preventing JavaScript Compilation for a Specific Folder using tsconfig: A Step-by-Step Guide

To create my own npx package, I'm currently working on converting my .ts files into .js. The purpose of the application is to generate TypeScript templates for users based on their selected options. In this app, there's a CLI called 'index.t ...

Utilizing Async and await for transferring data between components

I currently have 2 components and 1 service file. The **Component** is where I need the response to be displayed. My goal is to call a function from the Master component in Component 1 and receive the response back in the Master component. My concern lies ...

Encountering a fresh issue after updating to TS version 4.4.3 while accessing properties of the top "Object may be 'null'."

After upgrading my project to TypeScript 4.4.3 from 3.9.9, I encountered a change in the type declarations for the top property. My project utilizes "strictNullChecks": true, in its configuration file tsconfig.json, and is browser-based rather t ...

Choosing the primary camera on a web application with multiple rear cameras using WebRTC

Having a bit of trouble developing a web app that can capture images from the browser's back camera. The challenge lies in identifying which camera is the main one in a multi-camera setup. The issue we're running into is that each manufacturer u ...

Using ngClass for conditional styling in Angular 7: A step-by-step guide

Utilizing multiple classes within Angular's [ngClass] functionality is my current challenge. The goal is to make it function based on the flag condition provided by the component.ts file. ...

Using function overloading in TypeScript causes an error

I'm currently exploring the concept of function overloading in TypeScript and how it functions. type CreateElement = { (tag: 'a'): HTMLAnchorElement (tag: 'canvas'): HTMLCanvasElement (tag: 'table'): HTMLTableElem ...

Angular 2- Custom input forms sourced from various components for enhanced user experience

I am currently working on creating an angular 2 form using template-driven and I want to reuse a custom input that I have created. My main component structure looks like this: <form (ngSubmit)="onSubmit(f.value)" #f="ngForm"> <custom-in ...

Implementing a unique sorting algorithm for an array of numbers in Angular

I need to organize an array of numbers in descending order with a custom sorting method based on a specified number, all without splitting or filtering the array. I am currently working with Angular 17 and Rxjs 7.8. For instance, if I have this array of n ...

Receiving a SyntaxError in Node.js with the message "Unexpected token *" while attempting to import

node: v10.16.3 npm: 6.12.0 Encountered an error while trying to import express in node. Referencing the code from https://github.com/angular-university/rxjs-course, specifically server/server.ts. To run server.ts, used the following command: $ ts-node ...

Retrieve a specific value from the NGXS state by providing a parameter

I have a unique situation where my state contains JSON data like this: {id: "1", name: "ig1", description: "ig 11"} {id: "5", name: "hhh", description: "hhh"} {id: "6", name: "ggg", description: "hhh"} My goal is to specifically extract the data for id = ...

Converting JSON to string in Typescript is causing an error where type string cannot be assigned to type '{ .. }'

Here's the code snippet I'm working with: interface ISource extends IdModel { source_type_id: number; network_id: number; company_connection_id: number; feed_id: number; connection_id: number; feed_ids: number[]; name: string; tag ...

Omit certain table columns when exporting to Excel using JavaScript

I am looking to export my HTML table data into Excel sheets. After conducting a thorough research, I was able to find a solution that works for me. However, I'm facing an issue with the presence of image fields in my table data which I want to exclude ...

The MatTableDataSource provides a promise that includes approximately 7000 rows of data

When attempting to load a large amount of data into a MatTableDataSource, I am facing an issue. I would like to display a loader until the data is fully set, but I am unsure of when that happens. I attempted to use a promise like this: return new Promise(r ...

What is the best way to reset an imported file with each test in viTest?

I'm having trouble resetting an imported file completely after each test. I believe that using vi.mock should mimic the original contents of my imported file, but it doesn't seem to be working when I try to modify the file during the tests. Here ...

The 'type' property is not found on the 'never' type

There seems to be a typescript error showing up as Error: Property 'type' does not exist on type 'never' in the following code snippet: export const getSomething = (actionLog: [] | undefined) => { console.info(actionLog[length ...