What is the best practice for updating multiple fields within an ImmutableJS Record?

Looking for advice on updating multiple fields in an ImmutableJS Record efficiently.

I attempted to use withMutations, but encountered an issue where the copy I created was empty and could not be mutated:

const UserRecord = Record({
  firstName: null,
  lastName: null, 
  address: {
    city: null, 
    zipCode: null
  }
});

export function createUserRecord(data) {
  return new UserRecord(fromJS(data));
}

let u = createUserRecord({
  firstName: 'John',
  lastName: 'Don', 
  address: {
    city: 'New York', 
    zipCode: 1111
  }
});

let newU = u.withMutations((uCopy) => {
  // uCopy is empty (with default values)
  uCopy.set('firstName', 'New FirstName');
  uCopy.set('lastName', 'New LastName');
  // uCopy is still empty (not mutated)
});

console.log(u.toJS()); // {firstName: "John", lastName: "Don", address: {city: null, zipCode: null}}
console.log(newU.toJS()); // {firstName: null, lastName: null, address: {city: null, zipCode: null}}

Appreciate any help!

Answer №1

When using the withMutations method, the object u remains unchanged. Instead, it returns a mutated object that needs to be assigned to a new variable as shown below:

let newU = u.withMutations((uCopy) => {
  // uCopy starts off empty with default values
  uCopy.set('firstName', 'New FirstName');
  uCopy.set('lastName', 'New LastName');
  // The original object is still empty and not mutated
});

To understand this better, refer to the example in the documentation available at https://facebook.github.io/immutable-js/

var list1 = Immutable.List.of(1,2,3);
var list2 = list1.withMutations(function (list) {
  list.push(4).push(5).push(6);
});
assert(list1.size === 3);
assert(list2.size === 6);

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

How can you type a collection of initialized class instances in Typescript when given an object containing classes?

Imagine having an object that resembles the following: const typeMap = {category1: Category1, category2: Category2} In this case, Category1 and Category2 refer to classes, and there could potentially be hundreds of different categories. Now I also have a ...

A versatile method to organize a multi-dimensional array of items

I need help sorting a nested array using a generic function. The sorting should be based on the values of the items within the nested array. Here is an example of my array: type Person = { id: number, name: string, childs: Child[] } type Chil ...

"Dealing with cross-origin resource sharing issue in a Node.js project using TypeScript with Apollo server

I am encountering issues with CORS in my application. Could it be a misconfiguration on my server side? I am attempting to create a user in my PostgreSQL database through the frontend. I have set up a tsx component that serves as a form. However, when I tr ...

The Standalone Component does not appear for debugging in webpack:source when utilizing an incompatible version of Node

I have developed two components: https://i.sstatic.net/fSNqa.png However, after running ng serve, I am only able to see one component in the source of the Chrome browser: https://i.sstatic.net/VzdDS.png How can I troubleshoot this standalone component? ...

What are the reasons behind the compilation failure of the react-sortable-hoc basic example when using typescript?

Take a look at this sample code snippet extracted from the official react-sortable-hoc webpage. import React, {Component} from 'react'; ... // Code snippet goes here ... render(<SortableComponent/& ...

Place information from an input field into a specific row within a table

Utilizing Angular 4, I am developing a frontend application for a specific project. The interface features a table with three rows that need to be filled with data from an external source. https://i.stack.imgur.com/Dg576.png Upon clicking the "aggiungi p ...

React error: The DatePickerProps generic type must have one type argument specified

Date Selection Component: import React from "react" import AdapterDateFns from '@mui/lab/AdapterDateFns'; import { LocalizationProvider } from '@mui/lab'; import { DatePicker, DatePickerProps } from '@mui/lab'; cons ...

Testing exception - unstable FlushDiscreteUpdates

I am currently working on a test using Jest and react-testing-library for a .tsx test file written in TypeScript: import React from "react"; import { Provider } from 'react-redux'; import { render, screen } from "@testing-library/r ...

Ways to cite a vendor in static class functions?

Is there a method to access a service provided at bootstrap within static class methods? I don't have any code to share right now, but I've been experimenting with the standard syntax using Injector (you can find more information here). Whenever ...

Tips for enforcing strict typing in TypeScript when implementing abstract functions

Consider the following scenario with two classes: abstract class Configuration { abstract setName(name: string); } class MyConfiguration extends Configuration { setName(name) { // set name. } } In this setup, the name parameter in M ...

How do I designate the compiled migration location?

Currently, I am utilizing the PostgreSQL database ORM Sequelize along with TypeScript as a backend script within the Express Node.js environment. My first inquiry is: Is it possible to directly create a model in .ts format? The second question pertains t ...

How can a div be displayed next to another div when it is clicked using angular2?

Is there a way to have another page show up after clicking on a div, like shown in the image below? Before Click: https://i.sstatic.net/qSBbc.png After Click: https://i.sstatic.net/julH4.png ...

Distinguishing between TypeScript versions 2.0.x and 2.1.x using type definitions and filtering with a switch/case statement

@ngrx/store (an observable redux implementation for angular (2) ) utilizes a specific pattern to assign the correct type to a reducer. Check out the actual code here. export const ActionTypes = { FOO: type('foo'), BAR: type('bar&apos ...

Managing input fields with React Hooks, either in a controlled or uncontrolled manner

In my React Typescript application with hooks, I am working on setting a date input field in two different ways (controlled and uncontrolled). The field should update when the user inputs a new value or when the component receives props from its parent. H ...

I searched through the interface folder in the component.ts file but couldn't locate my typescript property

My coding dilemma goes something like this:- Within the interface folder, I have created a book.ts file with properties. However, my book.component.ts is not recognizing the book.ts property. It seems to work fine when I import the interface (book.ts) dir ...

How can I create a computed field in TypeORM by deriving its value from other fields within the same Entity?

My goal is to implement a 'rating' field in my User Entity. Within the User Entity, there exists a relationship with the Rating Entity, where the User has a field called ratingsReceived that eagerly loads all Ratings assigned to that User. The & ...

Discover the most effective method for identifying duplicate items within an array

I'm currently working with angular4 and facing a challenge of displaying a list containing only unique values. Whenever I access an API, it returns an array from which I have to filter out repeated data. The API will be accessed periodically, and the ...

Retrieving the Object value in Primeng p-dropdown when there is a change in selection

In my p-dropdown, I am trying to extract the selected value. <p-dropdown optionLabel="name" [options]="things" placeholder="Select Thing" [(ngModel)]="input" (onChange)="getValue(input)"></p-dropdown> typescript: //each lin ...

Issue with data not being recorded accurately in React app after socket event following API call

The Application Development I have been working on an innovative app that retrieves data from the server and visualizes it on a chart while also showcasing the total value in a Gauge. Additionally, the server triggers an event when new data is stored in t ...

What is the purpose of the 'unique' keyword in TypeScript?

While coding in the TypeScript playground, I stumbled upon a situation where the term unique seems to be reserved. However, I haven't been able to find any official documentation regarding this. https://i.stack.imgur.com/eQq5b.png Does anyone know i ...