Modifying state fields within an ngrx reducer

I have a data structure defined as follows:

declare type Relation = {
_id?: string,
root : string,
oPrimary :string,
nodes : [Ontology]

}

declare type Ontology = {
    id : string,
    ont : string[]
}

In the reducer, the state is structured like this:

export interface RelatedBusinessState {
relation : Relation

}

Components are responsible for updating specific fields within this document, such as inserting or removing nodes. The data is stored in a MongoDB database, and read/write operations are handled by an @Effect calling a service.

Instead of updating the entire document with each minor change, I would like to use methods like @addtoset. Therefore, the @Effect needs to determine which selector and fields need to be updated.

What is the best approach for setting the state in the reducer function? Since the state is observable, any changes will automatically reflect in subscribers. If I introduce a new key like edit : {_id : thisid,...}, TypeScript errors occur in the @Effect stating that 'edit' does not exist on type Relation.

The @Effect saves the data, retrieves the updated document, and dispatches it to an UPDATE_COMPLETE reducer function for state update.

EDIT: Let me elaborate further. There may be no issue at hand aside from a misunderstanding. Here is my scenario.

I am observing state changes, and the component/view updates accordingly when the state changes in the reducer.

My backend storage only requires updated data to modify the document in its collection.

The nodes and ontologies frequently change in the component; additions or removals occur swiftly. I want these changes reflected promptly in the view.

An action call in the component might look similar to this, where addNode is a function dispatching the action:

addNode({ id : token, ont : ['Customer']});

The action creator appears as follows:

static ADD_NODE = '[Relations] Add Node';
addNode(node : Ontology) : Action {
return {
type : RelatedBusinessAction.ADD_NODE,    
payload : node
}
}

The @Effects handle the calls to the database.

@Effect nodeadd$ = this.updates$
.whenAction(RelatedBusinessActions.ADD_NODE
.map<Relation>(toPayload)

My query pertains to what exactly does toPayload return? Does it provide the updated state set in the reducer or the payload from the action?

Answer №1

I am curious about the behavior of the toPayload function. Does it return the updated state set in the reducer, or does it simply return the payload of the action?

The toPayload function actually just returns action.payload.

export function toPayload(action: Action) {
  return action.payload;
}

More info on the toPayload method here

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

Angular unable to retrieve data using Angularfire2

Having trouble retrieving data from the Real time Database on firebase. Read and Write permissions are set to public so no authentication is needed. The npm compilation is successful, indicating that the Angular-CLI code is correct. Following the document ...

Maximum allowable size of an HTTP request for application/json data

When I receive a json object with 5 fields, one being the base 64 of an image (maximum size 150 kb), my Express server's body parser throws a 413 error stating entity too large. How can I configure the limit of characters in the HTTP request? Should I ...

Design a unique TypeScript index type with properties `[key of Y]: Partial<X>` that, when paired with a `default: Partial<X>` property, do not remain partial themselves

Here are some TypeScript type definitions to consider: enum Environment { Local = 'local', Prod = 'prod' } type EnvironmentConfig = { isCustomerFacing: boolean, serverUrl: string } type DefaultBaseConfig<T> = { default ...

Inferring types from synchronous versus asynchronous parameters

My objective is to create an "execute" method that can deliver either a synchronous or an asynchronous result based on certain conditions: type Callback = (...args: Arguments) => Result const result: Result = execute(callback: Callback, args: Arguments) ...

Resolving the Challenge of Disabling typescript-eslint/typedef in Angular 13 with ESlint

I started a fresh project in Angular 13 and configured typescript-eslint by running the command below: ng add @angular-eslint/schematic I made changes to my .eslintrc.json file where I disabled the rules for "typescript-eslint/typedef" and "typescript-esl ...

Struggling to generate React Typescript application

After running the command in cmd: npx create-react-app my-app --typescript I expected my app to be in TypeScript, but when I opened the folder in VS Code, I noticed that all files in the src folder had a .js extension instead of .ts(.tsx) extensions. I ev ...

Retrieving routing information from directives within angular2

const APP_ROUTES: RouterConfig = [ { path: 'app/home', component: HomeComponent, data: { name: 'Home' } } ] Assuming the route configuration is set as displayed above, how can one ...

When using TypeScript, how can I effectively utilize the Component property obtained from connect()?

Software Development Environment TypeScript 2.8 React 16 Redux Foo.tsx interface IFooProps{ userId:number } class Foo extends Component<IFooProps>{ render(){ return <p>foo...</p> } } const mapStateToProps = (state: I ...

"Learn how to trigger an event from a component loop up to the main parent in Angular 5

I have created the following code to loop through components and display their children: parent.component.ts tree = [ { id: 1, name: 'test 1' }, { id: 2, name: 'test 2', children: [ { ...

Developing applications using the combination of Vue.js, JSX, and

While I have no issues using TypeScript with single file components (.vue files), I encountered problems when attempting to use it with JSX files. Two errors arise, one in my index.ts file. I'm uncertain if there was a mistake made in my configuration ...

Retrieving information from BlobStorage using Service.ts and triggering the NgOnit function

Within the service.ts module, I am fetching data from Azure Blobstorage and attempting to read its contents. service.ts import { Injectable } from '@angular/core'; import { environment } from '../../environments/environment'; import { ...

The TypeScript decorator fails to apply on the subclass

Issue As I work on my project, I encountered an error while trying to create a decorator for a class: Error: Type 'typeof Controller' is not assignable to type 'typeof MainController'. Cannot assign an abstract constructor type to ...

How can I display a modal with image options and image selection using Ionic 4?

Currently, I am developing an Ionic 4 Angular application and implementing an Ionic modal feature. I would like to include images in the modal, so that when a user clicks on them, they are displayed. ...

Integrate incoming websocket information with state management in React

I am facing a challenge in creating a timeseries plot with data obtained from a websocket connection. The issue arises when new values overwrite the previously stored value in the state variable. const [chartData, setChartData] = React.useState(null) Cu ...

Using TypeOrm QueryBuilder to establish multiple relations with a single table

Thank you for taking the time to read and offer your assistance! I am facing a specific issue with my "Offer" entity where it has multiple relations to "User". The code snippet below illustrates these relationships: @ManyToOne(() => User, (user) => ...

At what point are routed components initialized?

Here is a route setup I am working with: path: ':id', component: ViewBookPageComponent }, After adding this route, an error keeps popping up: Error: Cannot read property 'id' of null I haven't included a null check in the compo ...

Is there a way to inform TypeScript of the existence of a value?

I am facing an issue with the code below: options: { url?: string } = {}; if (!Checker.present(this.options.url)) { throw new Error('Options must have a url'); } new CustomUrl(this.options) This error is occurring because Custo ...

Enhance your Javascript code performance by efficiently identifying IDs within a list and linking them to a tree structure

Looking for a way to improve the performance of the logic used for iterating over tree data and applying 'dataState' to 'FAILED' if there are matching error ids. interface IData { id: string; label: string; . value: string; expa ...

Converting TypeScript into JavaScript files within an ASP.NET SPA application

As I work on my current project using ASP.NET spa and Vue.js, I have been serving the dist folder from the Vue.js client app statically. This dist folder contains the compiled result of the client app's /src directory, where all .Vue and .ts files are ...

Tips for implementing a coupon code feature on Stripe checkout in an Angular 8+ application

I need to implement an input option for entering coupons in the Stripe payment gateway when the handler is open on the front end. I currently have a Stripe window open and would like to provide users with a way to enter coupon codes. // Function to Load ...