Utilizing Angular 2 alongside ngrx/store for seamless updates to specific properties within the state object without disrupting the entire structure

I am facing an issue where I need to update a property of a state object without creating a new object. Is there a way to add or update a single property without replacing the entire object?

Below is the reducer code:

const initialState = {
  all: [],
  single: {}
}

export const ModelsReducer: ActionReducer<any> = (state: IModelsStorage = initialState, action: Action) => {

  switch(action.type) {

    case GET_MODELS_SUCCESS: return Object.assign({}, state, {
      all: [...action.payload.data]
    });

    case GET_MODEL_SUCCESS: return Object.assign({}, state, {
      single: action.payload.data
    });
    
    // How do I only update the single object without overwriting the whole thing?
    case GET_VARIANTS_SUCCESS: return Object.assign({}, state, {
      single: {
        variants: action.payload.data
      }
    });

    default: return state;
  }
}

Can someone guide me on how to achieve this?

Answer №1

By using Object.assign once again...

switch (GET_VARIANTS_SUCCESS) {
  return Object.assign({}, state, {
    single: Object.assign(state.single, {
      variants: action.payload.data
    })
  });

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

Mapping HTTP responses to a Model in Angular 6

I'm currently looking into how I can effortlessly assign an http response to a specific model in Angular. My goal is to "push" the response into my model class, where only the properties defined in the model are assigned, ignoring all others. For ex ...

Is there a way to verify an if-else statement in the ngStyle background property with Angular 7?

I have a collection of cards that need to be shown in a component. Each card contains a cover-image with an URL fetched from the server. In my component.html, I am using ngFor as follows: <div [style.background-image]="'url('+row.companyId?.c ...

The OnPrepareResponse method in StaticFileOptions does not trigger when serving the index.html file

Currently, I am attempting to disable caching for index.html in my Angular SPA that is connected to a .NET Core 2.2 backend. I am following the instructions provided in this particular answer by implementing an OnPrepareResponse action for my StaticFileOp ...

The Unit Test for Angular NgRx is not passing as expected

I'm facing difficulties with my unit tests failing. How can I verify that my asynchronous condition is met after a store dispatch? There are 3 specific checks I want to perform: 1/ Ensure that my component is truthy after the dispatch (when the cond ...

Troubleshooting issue with Vue Class Component and Vuex-class causing ESLint error

I am interested in utilizing vuex-class to bind helpers for vuex and vue-class-component However, an error message is displayed: Error: Parsing error - Using the export keyword between a decorator and a class is not allowed. Please use `export @dec class ...

When utilizing express-handlebars to render, the error message "req.next() is not a valid function

Trying to display the login page of a web application. Developed using TypeScript, node.js, express, and express-handlebars The code being executed is as follows: import exphbs = require("express-handlebars"); import cookieParser = require(&quo ...

Utilizing React Custom Hooks for Firestore Data Retrieval

I recently developed a React custom hook that interfaces with a Firestore database. I followed the guidelines provided on the Firebase website, but I encountered an issue upon re-rendering the component. After refreshing my app, the useEffect hook function ...

The Function-supported Operation is having trouble implementing a modification related to Geohash/Geopoint - the Object Type requires a String format

Summary: My function-based Action that tries to set a GeoPoint as a Geohash property is failing with an error suggesting it was anticipating a string. I have an Object Type with a String property that has been designated as a Geohash in the property edito ...

An easy guide to adding animation to an image with just a click using angular-animations

I have a cool animation that currently triggers when the page loads. However, I want to change it so that the image animates on a button click instead. <div [@fadeInDownOnEnter]="'true'"> <img src="https://www.seoclerk.com/pics/5567 ...

React Formik - application triggers an undesired submission request when the Enter key is pressed in the input field

Whenever I enter a value in the "name" field and hit Enter, the app sends a request and the address bar in the web browser changes to http://localhost:3000/?name=something. However, if I simply add another input field to the form, the app's behavior c ...

Deriving a universal parameter from a function provided as an argument

My function can take in different adapters along with their optional options. // Query adapter type 1 type O1 = { opt: 1 } const adapter1 = (key: string, options?: O1) => 1 // Query adapter type 2 type O2 = { opt: 2 } const adapter2 = (key: string, opti ...

Is there a way to determine if there is history in Location.back in Angular 2 in order

I have a button that triggers Location.back(). I only want to show this button when there is history available. Is there a way to check if the location has any history, or if it can go back? Alternatively, is there a method for me to access the history my ...

Is emitting a side effect event acceptable within an RxJS pipe?

Currently, I am utilizing RxJS within the context of an Angular application. Within my service, there is functionality to reinitialize the entire application with different settings as needed. @Injectable() class BootstrapService{ public initApplicatio ...

As I attempt to log in, the GitHub API is sending back a message stating that authentication

const fetchUser = async () =>{ let usernameValue : any = (document.getElementById('username') as HTMLInputElement).value; let passwordValue : any = (document.getElementById('password') as HTMLInputElement).value; const ...

Resolving the active tab problem within Angular 2 tab components

Can anyone assist in resolving the active tab problem within an angular 2 application? Check out the Plunker link I am using JSON data to load tabs and their respective information. The JSON format is quite complex, but I have simplified it here for cla ...

What is the process for generating flexible paths (URL strings) in angular applications?

Within my <app-parent> component, I have multiple buttons that each open a new floating panel on top of the parent. These floating panels also contain buttons that trigger the opening of additional floating panels, creating a stacking effect. My go ...

The Static Interface Binding in TypeScript

I have inquired about how to extend the static functionality of existing objects in JavaScript (using TypeScript). In all examples provided here, I am utilizing Object The code below showcases a polyfill definition for ECMAScript's Object.is function ...

Sending an ArrayBuffer from Angular to Electron results in the window crashing

In my Electron application, I have integrated an Angular application internally. I am trying to download a byte array (ArrayBuffer) via an API call and then passing this data to a method connected through electron.remote.require('./file-service') ...

Using Kendo PanelBarItem to incorporate a personalized component as a child element

I was looking to design a component with PanelBarItems in its template. However, I'm facing issues and it doesn't seem to be working. Any suggestions? Main Component: import { Component } from '@angular/core'; @Component({ selecto ...

Every checkbox has been selected based on the @input value

My component has an @Input that I want to use to create an input and checkbox. import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core'; @Component({ selector: 'app-aside', templateUrl: './aside.component ...