Challenges in successfully utilizing the spread operator with a state object to achieve the desired outcome

In the Redux DevTools in Chrome, I have an initialization of the pimRegistration state shown below. The nesting being referenced is pimRegistration (state.domain.patient):

https://i.sstatic.net/inJRl.png

To update the patient.name object, I used the following spread operator statement:

store.update((state) => ({
  ...state,
  ...patientPath,
  ...{ [property]: value },
}));

Where property is the "name" property of the patient object with value. After the update, the new state is shown in the screenshot below:

https://i.sstatic.net/Zmfdb.png

Note that the original patient object (purple in the screenshot) is updated with the name object, duplicated and placed at the root of the state (yellow in screenshot).

I am looking to overwrite the properties of the

pimRegistration(state).domain.patient
object, rather than creating a new patient object.

The state update function is called as follows.

store.update((state) => ({
  ...state,
  ...patientPath, // state.domain.patient
  ...{ [property]: value },
}));

I have tried various combinations without achieving the desired result.


The complete update function is shown below.

update(property: string, path: string, value: any) {
  const paths: string[] = path.split(".");

  const pathReducer = (state: IRegistrationState, path_: string) => {
    if (paths.length <= 0) {
      return state.domain;
    }
    return state[path_];
  };

  const domainPath = state.domain;
  let patientPath, nokPath, referrerPath;

  if (path.includes("patient")) {
    patientPath = paths.reduce(pathReducer, state);
  }

  if (path.includes("nok")) {
    nokPath = paths.reduce(pathReducer, state);
  }

  if (path.includes("referrer")) {
    referrerPath = paths.reduce(pathReducer, state);
  }

  store.update((state) => ({
    ...state,
    ...patientPath,
    ...{ [property]: value },
  }));
}

The function above is called using the statement below in Angular 2.

if (this.path.includes("patient")) {
  this._repo.update("name", "domain.patient", this.name);
}

Thanks

Answer №1

Managing deep updates in a store can pose challenges. It appears that in your function, you are spreading the updates at the root level instead of directly where the update is needed. This provided answer explains the typical approach to updating the state. Essentially, something along the lines of:

const newState = {
  ...state,
  domain: {
    ...state.domain,
    patient: {
      ...state.domain.patient,
      [property]: value
    }
  }
}

Working with dynamic paths for state updates can be complex. While there are libraries like immer that can assist in this process, it is also possible to navigate through it using plain JS/TS.

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

Present pop-up messages in the most sophisticated manner

I have successfully created an AngularJS app that is functioning well. Now, I am faced with the challenge of displaying different pop-ups based on specific conditions being met. I am unsure of the best approach to take. Currently, I am considering two op ...

Utilize a select box to toggle between enabling and disabling options

Could someone please help me with enabling and disabling a text field based on a select box option? I'm not sure if I have written the code correctly below. If there are any errors, please correct me. <body> <table width="500" border="1"> ...

What is the best way to save data in order to effectively showcase a collection of images that together form a single entity in a game

Apologies for the unclear title, I struggled to find the right words. Recently, I delved into the world of 2D game development and was amazed by the capabilities of HTML5's Canvas element. Currently, I am working on my first basic project to grasp th ...

What sets apart a local node.js server from a basic python http server?

I am currently in the process of creating a D3.js chart on my local machine. Both my csv file and index.html are located in the same folder on my Desktop. Everything runs smoothly when I use my python local server, but I encounter issues when attempting to ...

Unable to store form data in a JSON file

i need help with the json data file called groups.json { "groups" : [ { "pname" : "group1", "remarks" : "best" }, { "pname" : "group2", "remarks" : "not the best" } , { "pname" : "group3", ...

The alert message fails to show up after the initial click on the close button

Whenever I click the x button to dismiss an alert message (indicating wrong data input in a form), the next time the user checks the form and enters incorrect data again, the alert message does not reappear after closing the x button. Any suggestions on ho ...

What is the best way to implement nested iterations in Jade?

ul li a(href='') menu1 li a(href='') menu2 ul li a(href='') sub-menu2 li a(href='') menu3 ul li a(href=&apos ...

Can a new frame be created below an already existing frame in HTML?

My main.html file looks like this: ----- main.html---------------- <title>UniqueTrail</title> <script src="main.js"></script> <frameset rows='200,200'> <frame id='one' src="f ...

A unique string containing the object element "this.variable" found in a separate file

Snippet of HTML code: <input class="jscolor" id="color-picker"> <div id="rect" class="rect"></div> <script src="jscolor.js"></script> <script src="skrypt.js"></script> Javascript snippet: function up ...

A Beginner's Guide to Duplicating Bootstrap Containers in Jade

I am working with JSON data that is being transmitted from an Express and Mongoose Stack to be displayed on the user interface created in Jade. I am wondering which Jade Construct I should use to loop through a Bootstrap Container of col-md-4 using Jade s ...

Once the node modules folder has been received, proceed with installing npm packages

Hello, my name is Jaffer Syed and I'm currently facing a challenge in installing npm packages into my code. Specifically, I am trying to install the num2fraction package from https://www.npmjs.com/package/num2fraction. However, despite watching your n ...

Correcting the reference to "/" (root) for assets after relocating the site to a subdirectory

I currently have a website located in the public_html directory, where all assets (images, css, js, etc) are referenced using /asset_folder/asset. The "/" at the beginning ensures that the browser starts from the root and navigates through the directories. ...

Error message: Failure to define class methods when exporting the class from a file

In my project, I have defined a class called BinarySearchTree in a file named a.js. This class has been exported and then imported into another file where it is used as the parent class for a different class called Traversal. However, I encountered an issu ...

Having trouble verifying a phone number using the awesome-phonenumber npm package?

I recently developed some JavaScript using the awesome-phonenumber npm package. index.js const yargs = require('yargs'); var PhoneNumber = require( 'awesome-phonenumber' ); const argv = yargs .usage('Usage: $0 -n [num]' ...

Losing concentration when entering a character

Here is the code I am working on. Having an issue with the focus on password, password confirmation, and email inputs within the Sign-up modal. When typing a character, it loses focus automatically. Any suggestions on how to fix this? I have already tried ...

Leverage the power of Angular CLI within your current project

I am currently working on a project and I have decided to utilize the angular cli generator. After installing it, I created the following .angular-cli file: { "$schema": "./node_modules/@angular/cli/lib/config/schema.json", "project": { "name": " ...

Is it possible to showcase particular object values within an array rather than displaying them individually?

I have utilized an ajax call to fetch data from the Google Places API and implemented a for-in loop to extract the information. Although the desired information is being logged to the console, I am having trouble organizing it into an array as per my requi ...

Utilize the jQuery function for both resizing and loading events without the need for duplicating code

As I review this piece of jQuery code that checks the browser width upon loading and adjusts accordingly, I find it redundant to also duplicate it within the $(window).resize(function() {..});. Is there a more efficient way to run the code just once for ...

The slideUp function is not functioning as expected

I am trying to implement a slideUp effect on my webpage. Here is the code within my <body> tag: <script> $('#slide_up').click(function(){ $('p.text_study').slideUp('slow', function() { $ ...

What is the best way to vertically align an InputLabel within a MUI Grid item?

I'm trying to vertically center the InputLabel inside a MUI Grid item. Here's what I've attempted: import { FormControl, Grid, Input, InputLabel, TextField } from "@mui/material"; export default function App() ...