Using Angular Store to update individual objects when they are updated

Currently, my project utilizes the '@ngrx/store' to store data locally for display in a table. A key component of this functionality is the ability to edit and update user information.

All necessary setup such as user actions, effects, reducer, and selector have been completed. Data is accessed from a remote database via an API connection.

One challenge I am facing is that when I have a list of users stored in memory, I encounter difficulties editing them. It appears that in order to update a user, I must clone the object, make changes, and then pass it to the update function.

Despite these efforts, I have been unable to successfully update the local in-memory copy of the users array state without needing to retrieve all data from the remote server again.

Here is a snippet of my reducer code:

case Actions.UPDATE_SUCCESS: {
      let user= action.payload as User;   
      let position = state.data.findIndex(x => x.id === user.id);
      let temp: User[] = _omit(state.data, position);
      temp.splice(num, 0, test); //This function outright fails to execute
      const newState = {
        ...state,
        usersData: temp
      }
      return newState;
    }

I am curious if there are more efficient ways to approach this situation?

Answer №1

If you want to update an existing object in an array of objects with a newly updated object, you can simply do so by comparing IDs.

In the code snippet below, the state.data.map.... statement iterates over the user array and checks if the user ID matches the ID of the newly updated user. If there is a match, it replaces the existing record with the updated one.

case Actions.UPDATE_SUCCESS: {
   const updatedUser = action.payload;
   return {
    ...state,
    usersData: state.data.map((user: User) => (user.id === updatedUser.id ? updatedUser : user))
   };
  }

Answer №2

The map() function is a handy tool for transforming arrays. It creates a new array based on the elements of the original one.

Redux and NGRX focus on maintaining immutable state in an application. This means that each state remains unchanged once set. When a new action occurs, it uses the current state to produce a fresh state, preventing accidental modifications through mutable operations. Additionally, this approach helps us trace back which actions influenced the current state.

return {
...state,
userData: state.userData.map(uData =>
    udata.id === action.payload.id ? action.payload as User : uData
}

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

Interpolating Attributes and Properties in Angular

My usual approach for property binding is as follows: <a [href]="myHref">Link</a> (where myHref represents a property in my Component class.) However, I have come across a different method on the Angular website where they use: <a href=" ...

Prevent scrolling using mousewheel click (auxclick event)

Currently working with Angular 9 and encountering an issue with the (auxClick) event triggering on a mousewheel click. The problem arises when attempting to use this event while there is a scroll present on the page, as it does not trigger correctly due to ...

What is the best way to implement Angular 2 Material Sidenav within a component?

I am a beginner in the world of angular and I am trying to navigate my way through. The documentation for the new angular 2 material can be a little overwhelming, but I was able to successfully add tabs and a sidenav to my app. However, I am struggling to ...

Encountered Angular 7 Error: Unable to access pro due to TypeError

I've encountered an error in my Angular front-end application: https://i.sstatic.net/koqvm.png Error: index.js:3757 TypeError: Cannot read pro Here's what I have tried so far: I inspected the code but couldn't find the root cause of t ...

The NodeJS application experiences a crash if incorrect parameters are provided to the API

Currently, I have built a CRUD API using TypeScript with Node.js, Express, and MongoDB. My goal is to ensure that the API functions correctly when the correct parameters are sent through a POST request. However, if incorrect parameters are passed, the Node ...

How can I transfer an instance of a class to dataTransfer.setData?

So I created a new instance of a class: let item = new Item(); Next, I attempted to serialize the item and add it to dataTransfer for drag and drop functionality: ev.dataTransfer.setData("info", JSON.stringify(item)); At some point, I need to retriev ...

Utilizing Vue 3/Nuxt 3 Scoped Slots to Automatically Deduce Generic Data Types from Props

I am looking to incorporate a carousel component into Nuxt v3. The component will be passed an array of items, focusing solely on the logic without handling styling or structuring. Currently, this is what my component looks like: components/tdx/carousel. ...

Vue: rendering props cannot be utilized with TSX

After switching my setup from JSX in a Vue component to TS with vue-class-component, I found that only the code snippet below works for me (as shown in the example on repo): import Vue from 'vue' import { Component } from 'vue-property-dec ...

Issue with Angular 6 and Chrome: Event listener ($event) occasionally throws the error "unable to access property 'value' of null"

It appears that the buttons are being iterated correctly using ngFor, and upon inspection they have the correct attributes. However, when clicked, the function in the controller sometimes claims the parameter is 'undefined', happening randomly ab ...

Capturing Angular 4 Screenshots with html2canvas

Is there a way to capture and send a screenshot using html2canvas in Angular 4 via an HTTP POST request? Component import { Component, OnInit, NgZone } from '@angular/core'; import { Router, ActivatedRoute, Params } from '@angular/rout ...

What methods does VS Code use to display type errors in TypeScript given that TypeScript requires compilation?

TypeScript is a language known for being statically typed, giving it the ability to verify types during the compilation process and translate the code into JavaScript. Considering this, how is it possible for VS Code to detect type errors without the code ...

Unable to showcase the content inside the input box

I am having trouble displaying a default value in an input field. Here is how I attempted to do it: <input matInput formControlName="name" value="Ray"> Unfortunately, the value is not appearing as expected. You can view my code o ...

`Inconsistencies in console.log output with Angular Firestore``

I'm currently working on retrieving the id of selected data, but when I test it using console.log, it keeps outputting twice. The image below illustrates the console.log output. https://i.stack.imgur.com/IARng.png My goal is to fetch the id once and ...

Fetching the value of ngModel from within ngFor loop - a step-by-step guide

<div class="form-horizontal" style="margin:auto;" *ngFor="#cmp of getUser"> <div class="form-group"> <label class="col-md-3 control-label">Name:</label> <div class="col-md-8"> <input type="te ...

What is the best way to extract a property if it may be undefined?

Can anyone help with this TypeScript error I'm encountering during build time? Any suggestions would be appreciated. Error Message: TypeError: Cannot destructure property 'site' of '(intermediate value)' as it is undefined. export ...

Encountering problems with displaying the index value in *ngFor directive in Angular 5

I am encountering a problem with rendering the index of *ngFor directive for a specific scenario as described below. Suppose we have an array of objects like this: this.temp = [ {name:'John',age:24,visibility:'visible'}, {name:&ap ...

What is the process for transferring data processed in Python to Node.js and then forwarding it to Angular?

I am a newcomer to Angular and I'm looking for a way to showcase JSON data from Python in my Angular app using Node.js. I have already utilized child processes to establish the connection between Python and Node.js, but I am facing a challenge on how ...

What method can be used to seamlessly integrate Vue.js into a TypeScript file?

The focus here is on this particular file: import Vue from 'vue'; It's currently appearing in red within the IDE because the necessary steps to define 'vue' have not been completed yet. What is the best way to integrate without r ...

An issue occurred while attempting to differentiate '[object Object]'. The only permissible inputs are arrays and iterables

I encountered the following error message: "ERROR Error: Error trying to diff '[object Object]'. Only arrays and iterables are allowed" during runtime. My goal is to fetch a JSON response and display it in tabular format on the UI. Please r ...

Creating an interactive webpage with Javascript and HTML

I'm facing a challenge with my component setup, which is structured as follows: import { Component, VERSION } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: [ ...