Strategies for updating nested objects in Redux without altering their original structure

I'm diving into the world of Redux and feeling a bit confused about how to update data without mutating it.

Here is my current data structure:


{
  postOwnerName:"",
  postTags:[],
  photos:[
    {  
      id:dc5c5d7c5s,
      caption:null
    },
    {  
      id:dccccccc5s,
      caption:null
    }
  ]
}

When the function triggers with this line of code:

this.props.updateCaption(id, caption)

I want my Reducer to update the data structure based on the provided id without mutating it.


import * as types from '../Actions/actionTypes';

const initialState = {
  postOwnerName:"",
  postTags:[],
  photos:[],
};

export default function uploadReducer(state=initialState, action) {
  switch (action.type){
    case types.SETPHOTOSTATE:
      return Object.assign({}, state, { photos: state.photos.concat(action.payload) });
    case types.SETCAPTIONTEXT:
      return (
        Object.assign({}, state, {
          photos: state.photos.map((data) => {
            if(data.id === action.payload.id) {
              return Object.assign({}, data, {caption: action.payload.caption})
            } else {
              return data
            }
          })
        })
      )
    default:
      return state
  }
}

Answer №1

When the state object contains multiple levels, it can become challenging to alter the state without mutating it. In such cases, I opt to deeply copy the state first, then make modifications to the new state before returning it. Refer to this resource on deep cloning objects. Give it a try.

export default function uploadReducer(state=initialState,action) {
  let newState = JSON.parse(JSON.stringify(state));
  switch (action.type){
    case types.SETPHOTOSTATE:
       newState.photos.push(action.payload);
       return newState;
    case types.SETCAPTIONTEXT:
       newState.photos.map((data) => {
         if(data.id == action.payload.id){
           data.caption = action.payload.caption;
         }
       });
       return newState;
   default:
     return newState;
   }
}

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

Utilizing Header and Footer Components in React JS

I'm new to Reactjs(Nextjs) and I am looking to create a "header" and "footer" file that can be used on all pages. I would like to know the best approach to achieve this. Should I create a "Layout.js" file and then call the Header within it? Or should ...

What is the best way to eliminate HTML <li> bullets using codebehind?

When working in codebehind, I often create an HTML list using the following method: HtmlGenericControl list = new HtmlGenericControl("ul"); for (int i = 0; i < 10; i++) { HtmlGenericControl listItem = new HtmlGenericControl("li"); Label textLabel ...

Is it possible for a Javascript code to execute multiple tasks upon being inserted into the browser's URL bar?

Is it feasible for JavaScript to simulate a user clicking on a link, triggering a pop-up, automatically clicking a button within the pop-up, and then redirecting the user to a final page once a specific code is copied and pasted into the browser's add ...

Tips for simultaneously saving user data to the database and showcasing their input on the screen

I have a function in my JavaScript file that displays user data on the screen, but it's causing issues with saving data to the database. I want both functionalities - displaying on the screen and saving to the database without any conflicts. Edit: My ...

React Native's SQLite storage library does not seem to be providing any response

Currently, I am utilizing the SQLite database through react-native-sqlite-storage. However, when attempting to display the result in an alert, it shows as undefined. I have also attempted performing the operation without using await and async. MainFil ...

How to implement saving TypeScript Map() in Firebase Cloud Functions?

I am currently developing a Firebase Cloud Functions application using TypeScript that is designed to save an instance of Map() to Cloud Firestore. The map consists of user IDs as keys and objects with 2 simple attributes as values. Due to the dynamic natu ...

"Utilizing the react-router onEnter hook to establish a connection with the redux store - here's

I'm attempting to utilize the onEnter hook in react-router to validate a variable in my redux store when navigating to a new route. As per the documentation, the onEnter function: ...receives the next router state as its first argument. The replac ...

What causes the variable "change" to display unexpected results?

Why isn't the function working as expected? I need the change to be 0. I believe there must be a more efficient way to solve this issue, but what's bothering me is that the "change" variable is giving strange values...need help! function checkCa ...

Error: The JavaScript variable 'undefined' is being used as a function, which is incorrect. This error occurs when trying to execute the function `mockBackend

I am currently working on unit testing an AngularJS controller using Karma and Jasmine. Below is the test suite I have created: describe('Controllers', function(){ var $scope, ctrl; beforeEach(module('curriculumModule')); ...

Uncovering the Solution: Digging into a Nested ng-repeat to Access an Array in AngularJS

I am working with a recursive array in JavaScript: [{ type: 'cond', conditionId: 1, conditions: undefined }, { type: 'cond', conditionId: 2, conditions: undefined }, { type: 'group', conditionId: undefined, ...

A step-by-step guide on setting --max-old-space-size using the npm link command

Can the --max-old-space-size parameter be configured using npm link? I am aware that it can be set using the node command such as node --max-old-space-size=, but I am attempting to achieve the same result through the npm link command. Is this feasible? Yo ...

Refresh the page and navigate to the last active tab using PHP and jQuery jTable

After a user clicks the submit button on a jquery-jtable form, I am trying to reload the page and navigate to the tab that was active before the reload. However, my current solution only reloads the page without navigating to the previous tab. The tabs are ...

Feeling lost about arrow functions in JavaScript

Here is the code I am currently using to increment the value of intVariable using window.setInterval. var Arrow = (function () { function Arrow() { this.intVariable = 1; this.itemId = -1; this.interval = 25; } Arrow.p ...

Saving file with HTML download button results in only HTML document being saved

I am attempting to include a "download file" button on my gatsby website as shown below: <a href="../../images/project-logos/placeholder-company-logo.png" download="test" className="responsive-square project-logo" > <img sr ...

Trigger the Material UI DatePicker to open upon clicking the input field

I have a component that is not receiving the onClick event. I understand that I need to pass a prop with open as a boolean value, but I'm struggling to find a way to trigger it when clicking on MuiDatePicker. Here is an image to show where I want to ...

Tips for accessing req.fields variables while utilizing Express-Formidable

For some reason, I am encountering difficulties when trying to access variables parsed within req.fields using Express-Formidable. Upon executing a console.log() of req.fields, the output is as follows: { 'registration[username]': '1', ...

What is the best method for snapshot testing a component that includes nested components?

I am currently testing a component that contains a nested component using Redux. To test this, I am utilizing shallow rendering. Below is the code for my test: describe("Header", () => void it("renders correctly", () => { const renderer = new ...

IE11 encounters an error labeled SCRIPT1010, signaling an expected Identifier when compiled

Lately, I've been encountering a strange issue in Vue.js. Here's the thing: my application runs smoothly on all browsers locally (yes, even IE 11). But when I compile it using npm run build and deploy it to my server (which essentially serves con ...

XMLHTTPRequest fails to retrieve a valid response

Similar Question: Approach for Retrieving BLOB Data from XHR Request In my attempt to dynamically retrieve an image from the server, I am encountering an issue where the XMLHTTPRequest response is returning null. Despite indications from the Google Ch ...

Is it possible to create a JSON file using JavaScript?

Is it possible to create a webpage on "example1.com" that retrieves and parses a JSON file from another domain, like "example2.com/json.json", using JavaScript? I know this can be achieved with PHP, but I prefer using JavaScript. If generating a JSON file ...