The process of updating a nested object property in Redux and React

Initially, the user object is established with properties such as name, color, and age using the SET_USER method. I need to modify the name property within the user object utilizing UPDATE_USER_NAME. However, despite trying a nested loop within UPDATE_USER_NAME, the name attribute remains unchanged.

What mistake am I making? If I attempt something like

user: {action.name, ...state.user}
, the user object gets updated successfully. Nonetheless, this action results in the creation of a new property from action.name instead of updating the existing name within the user object.

const DEFAULT_STATE = {
  user: {},
}

export default function(state = DEFAULT_STATE, action) {\
  switch(action.type) {
    case actionTypes.SET_USER:
      return {
        ...state,
        user: action.user,
      }

    case actionTypes.UPDATE_USER_NAME:
      return {
        ...state,
        user: {
          name: action.name,
          ...state.user,
        }
      }

    default:
      return state
  }
}

Answer №1

To modify the spread order slightly, all you have to do is:

case actionTypes.UPDATE_USER_NAME:
      return {
        ...state,
        user: {
          ...state.user,
          name: action.name,
        }
      }

By using this approach, user will be updated with the existing state.user data before changing the name field. The spread operation functions similarly to Object.assign (from left to right). This is due to the fact that when identical keys are assigned in an object literal, the value from the last one declared takes precedence.

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 I ensure a header is displayed on each page by utilizing CSS or JavaScript/jQuery?

On a lengthy page with approximately 15 pages of text, I would like to insert a header at the beginning of each page when the document is printed by the user. Can this functionality be achieved using CSS or JavaScript/jQuery? ...

What distinguishable characteristics can I look for to differentiate between code written in React and code written in React Native?

I stumbled upon a project on GitHub that gives the impression of being a mobile application when executed. However, upon reviewing the code, it appears to have been developed using React rather than React Native. Is there a definitive method to verify thi ...

Create a list using ng-repeat in AngularJS, each item separated by "custom categories"

I am looking to create a dynamic list that will display values entered by users, categorized by custom categories. The challenge is that I do not know in advance which category each element will belong to. Here's an example of how I envision the list ...

Is there a way I can maintain the active state after clicking on a link?

Is there a way to maintain an active element state when navigating to another page after clicking a link? I am wondering if it is possible to use JavaScript to remove the active state from one link and apply it to the next one. I am facing some challenges ...

Incorporating and utilizing the HTML5-captured image as a point of reference

I understand that all I need to do to achieve this is insert <input type="file" id="photo" accept="image/*;capture=camera"> However, my lack of coding skills has caused issues with actually grabbing and using the image selected/taken by the user. ...

Guide on integrating react-tether with react-dom createPortal for custom styling of tethered components based on their target components

Within a Component, I am rendering buttons each with its own tooltip. The challenge is to make the tooltip appear upon hovering over the button since the tooltip may contain more than just text and cannot be solely created with CSS. The solution involves ...

What is the purpose of employing useMemo in the Material-UI autocomplete documentation?

My focus is on this specific demo in the autocomplete documentation. In the google maps example, there is a throttled function that is returned from a useMemo with an empty array as the second parameter. However, it raises the question of what exactly is ...

Troubleshooting the failure of implementing react hooks useState within a material-ui Tab container

Recently, I have been experimenting with implementing react-hooks useState in material-ui/tabs component. While I have been successful in using the handleChange function, I am eager to explore and master the use of hooks in this scenario. Interestingly, my ...

Error: Unable to locate module 'react-calendar-heatmap'

After successfully creating a component that functioned flawlessly in my local application, I encountered an error when attempting to integrate it with npm: ./src/App.js Module not found: Can't resolve 'heatmap-calendar-react' in 'C:& ...

Expanding Vue JS Vuetify Panels in a V-for Loop to Reveal Multiple Panels

When pulling data from a database and looping through it in the DOM using a "v-for" loop, I encountered an issue with Vuetify expansion panel components. The problem is that when a user clicks to open one expansion panel, it ends up opening all other panel ...

The function getServerSideProps is not defined in the NextJS environment

I am facing an issue where I need to pass an array called initialPosts into my Home function using getServerSideProps, but the props are showing up as undefined. Despite trying various solutions, none of them seem to work. In getServerSideProps, I have us ...

Tips for fixing label overlap problem in React Material UI autocomplete component

I recently started working with React Material UI and I am looking to implement a floating label for the auto complete component. However, once a value is selected from the auto complete options, I want the label to stay at the top. For further clarifica ...

Updating the state of a React Component using data from 2 input fields

I am facing an issue with two input fields of type "file" in a React component. My goal is to load a JSON file into each input field, save the data from both files into separate variables, and update the state of the component. However, I have noticed that ...

Click on each item within the v-for loop to gather relevant information, and subsequently iterate through the collected data

Within a v-for loop, I have implemented a button that, when clicked, retrieves specific data. The objective is to display this data below or in place of the clicked button. <div v-for="(item, index) in items" :key="index"> <button @click="fetch ...

How to ensure NodeJS waits for a response before returning a value

I've come across a seemingly simple problem that I just can't seem to solve. My current project involves working with an asynchronous messaging bot. In this particular scenario, the bot is supposed to react to an event by calling a Restful API a ...

Unlocking the ability to retrieve data generated by the context within getServerSideProps beyond its boundaries (for transitioning from Create React App to Next.js)

I am currently utilizing Create React App for my react application but I am in the process of migrating to Next.js. Accessing URL data such as host, protocol, and query parameters has posed a significant challenge. After some trial and error, I realized t ...

The process of uploading a React App to Heroku resulted in a critical error: "FATAL ERROR: Heap limit reached, Allocation failed - JavaScript heap out of memory."

There's a puzzling issue that I believe I have the solution to (paying for more bandwidth on Heroku), but the root of the problem eludes me and it's truly frustrating. Any assistance in pinpointing the cause would be greatly appreciated! Hopefull ...

Please ensure that the property name is a valid type, such as 'string', 'number', 'symbol', or 'any'

Can anyone help me convert this JavaScript file to Typescript? import React, { useState } from 'react'; import { Button } from './Button'; import { Link } from 'react-router-dom'; import './Navbar.css'; import Settin ...

Tips on hiding bottom tabs when navigating to a route that is two levels deep

When a specific screen is active, I want the bottom tab bar to disappear. Using react navigation for this purpose. For example, when the "Insight Detail Adjustment" screen is displayed, I need the bottom tabs to be hidden. Currently, none of the solutions ...

Customize the Color of Your Material-UI Drawer

Need help with setting the background color of a Material-UI Drawer. I tried using the following code but it didn't work: const styles = { paper: { background: "blue" } } After defining the styles, I passed them to the Drawer component like ...