Issue when attempting to update the state using the spread operator

I'm currently developing a react application and I've encountered an issue. My goal is to update the state object within my reducer using parameters supplied by the action creator. To simplify, I've created an example in pure JS

Here is how my State Object looks:

const stateObj = {
  left: {
    data: [{ name: 'Adam', surname: "Test Adam" }]  
  },
  right: {
    data: [{ name: 'Tom', surname: 'Test Tom' }]  
  },
}

The data received by the reducer from the action creator is structured like this:

const id = 0; 
const newValue = "Sample new value"; 
const nameOrAge = 'name'; 
const leftOrRight = 'right'; 

Based on these parameters, the result should be a deep copy of the state object with one property changed to name: 'Sample new value':

left: {
     data: [{ name: 'Adam', surname: "Test Adam" }]  
   },
   right: {
     data: [{ name: 'Sample new value', surname: 'Test Tom' }]  
   },
 }

This is what I have so far - a sample reducer function:

const showModifiedData = (id, newValue, nameOrAge, leftOrRight) => {
  // Need help modifying the data array
  return {
    ...stateObj,
    [leftOrRight]: {
      ...stateObj[leftOrRight],
      data: // modify the name property based on parameters
    }
   
  }
  
}

I'm having difficulty properly altering the data array. Any assistance would be greatly appreciated.

Answer №1

To update the specific property in each object of the data array, you can use stateObj[leftOrRight].data.map().

const stateObj = {
  left: {
    data: [{ name: 'Adam', surname: "Test Adam" }]  
  },
  right: {
    data: [{ name: 'Tom', surname: 'Test Tom' }]  
  },
};

const id = 0; // Identifies the item to modify
const newValue = "Sample new value"; // New value for the property
const nameOrAge = 'name'; // Specifies which property to change
const leftOrRight = 'right'; // Indicates which part of the state to modify

const showModifiedData = (id, newValue, nameOrAge, leftOrRight) => {
  return {
    ...stateObj,
    [leftOrRight]: {
      ...stateObj[leftOrRight],
      data: stateObj[leftOrRight].data.map((el, i) => i == id ? {...el, [nameOrAge]: newValue} : el)
    }
  }
}

console.log(showModifiedData(id, newValue, nameOrAge, leftOrRight));

Answer №2

There are various strategies that can be employed. One method involves duplicating the array by using either slice or spread, and then assigning the new object at the specified index.

For instance

const updateDataEntry = (id, newValue, nameOrAge, leftOrRight) => {
    const dataset = [...stateObj[leftOrRight].data];
    dataset[id] = {...dataset[id], [nameOrAge]: newValue};
    return {
        ...stateObj,
        [leftOrRight]: {
            ...stateObj[leftOrRight],
            data: dataset,
        }
    }

}

It is important to note that with this method, only the modified object is duplicated, while the rest continue to reference the original objects.

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

Creating immersive visualizations using Three.js and WebGL, as well as leveraging 2D canvas for rendering graphics, involves passing the getImageData

Recently diving into WebGL (and 3D graphics in general) using three.js, I'm looking to create multiple textures from a 2D canvas for rendering various meshes, each with its own unique texture. Simply passing the canvas to a new THREE.Texture() causes ...

Transfer the array using Ajax to a PHP script

I have an array generated using the .push function that contains a large amount of data. What is the most effective way to send this data to a PHP script? dataString = ??? ; // Is it an array? $.ajax({ type: "POST", url: "script.php" ...

Can you rely on a specific order when gathering reactions in a discord.js bot?

Imagine a scenario where a bot is collecting reactions to represent event registrations. To prevent any potential race conditions, I have secured the underlying data structure with a mutex. However, the issue of priority still remains unresolved as user # ...

Ways to display JSON data in Angular 2

My goal is to display a list of JSON data, but I keep encountering an error message ERROR TypeError: Cannot read property 'title' of undefined. Interestingly, the console log shows that the JSON data is being printed. mydata.service.ts import { ...

The animation in threejs using lerp and camera transitions lacks fluidity

Why does linear interpolation pose a problem? When calling zoomCamera() inside an update() function that is being animated, there is a smooth lerp effect. However, when called within the onObjectsClick() function, the lerp is sharp. function onObjectsCl ...

The troubleshooting of debugging javascript remotely on IntelliJ with the JetBrains Chrome extension is proving to be unsuccessful

I've been attempting to set up a debugger for some JavaScript files that I'm working on in IntelliJ (version 2020.1.4). Following the guidelines provided here Debug with JetBrains Chrome extension, I believe I have successfully completed all the ...

Error thrown when attempting to access properties of null values (Uncaught TypeError: Cannot read properties of undefined (reading 'map'))

import React, { useState, useEffect } from "react"; import { TaskLists } from "./TaskLists"; import { Daycard } from "./daycard"; import { getTasks, deleteTask } from "../api/task.api"; export function TaskManager() { const [tasks, setTasks] = useState( ...

Identifying Inactivity in Cordova Android Applications

Hey there! So, I've created a flashlight/torch app that can be found at the following link: https://github.com/Skelware/Fancy-Flashlight. This app utilizes a Cordova plugin available here: https://github.com/Skelware/Cordova-Flashlight. For now, my m ...

What strategies can I employ to optimize this code in RXJS and Angular?

Is it possible to streamline these nested arrays for more efficient execution after all subscriptions have been completed? I believe there may be a solution involving the use of pipes, mergeMaps, concatMaps, etc. this.teams = [ { Assignments: [{Id: ...

Tips for waiting for a function to finish executing in node.js (using a for loop)

Currently, the issue lies in the fact that the for loop instantly loops through everything. However, I want it to pause before looping because each time the loop runs, it inserts data into the database (which takes time). Therefore, I would like it to wait ...

Display a collection of objects using Jade / Pug syntax

Struggling to find resources on Pug / Jade templating, turning to this platform for help. I've been diving into documentation on iterations along with consulting this helpful link. Working with Node.js, Express, and pug for a school project - a mock ...

error message: The file you are trying to access does not exist due to the

I seem to be facing an issue with my package.json file. I am trying to include a new "command" in a correctly written package. Specifically, I am looking to add a command that will load test data, so I updated the scripts section as follows: "load-test-da ...

What is the process for populating dropdown options from state?

I've been struggling to populate a select element with options based on an array in state. Despite trying various methods, the code snippet below seems to be the most detailed (I'm still getting familiar with React after taking a break for a few ...

Array specifically designed for replacing strings, but it only works with the final element

Here is a snippet of code I am working with: $(document).on('click','.submitMessage,.submitStdMessage', function(e){ prevContent=$('textarea').val(); alert(prevContent); variables = { '{nom}' ...

Function compilation did not succeed in the module

I've put together a MERN (MongoDB, ExpressJS, React, Node) project using express-generator (express myNewApp). Within a react component, I have implemented this ES6 code snippet: onChange = (event, { newValue }) => { // Line 53 this.setSt ...

When the user presses either the refresh button or the back button, they will be redirected

After the user presses refresh or uses the browser back button, I need to redirect them to a specific page in order to restart the application. My JavaScript code is as follows: var workIsDone = false; window.onbeforeunload = confirmBrowseAway; function ...

Managing Session Cookies in ExpressJS

Hey there! I've been dealing with a problem while using Express-Session to manage my server-side sessions. When I set user data to session variables in one file, it works perfectly. However, when I try to access those variables in another file, all I ...

Is there a way to prevent users from selecting certain days in ion-datetime?

After searching through the official documentation, I couldn't find a solution. I am in need of a function similar to the jQuery datepicker beforeshowday function. My goal is to disable all weekends (Saturday and Sunday) in upcoming dates so that user ...

Error in Layout of Navigation Panel and Tabbed Pages

Working on a school project, I encountered a challenge. I found two useful solutions from the W3 website - a sticky navigation bar and the ability to include tabs on a single page for a cleaner presentation of information. However, when trying to implement ...

Converting a text area into a file and saving it as a draft in the cloud with the

Can content from a text area be converted into a file of any chosen format and saved in the cloud? Additionally, should every modification made in the text area automatically update the corresponding file stored in the cloud? ...