react redux merge state with given array

redux update item in array
state.merge immutable
redux remove an item from an array
redux remove item from object
state merge react
redux replace entire state
redux-immutable
redux immer

Lets say I have a reducer which is like :

const initialState = [
  {
    accessToken: null,
    isLoggedIn: false,
  }
]

export default function my_reducer(state = initialState, action) {
  switch (action.type) {
    case LOGIN:
        return state.merge(user: action) ---> how to handle this 

and the output should be like:

[
      {
        accessToken: null,
        isLoggedIn: false,
        user: {
            name: 'some name',
            email: 'some email'
      }
    ]

In action I am getting a array which I am providing by doing JSON.stringify(response)

previous data should not be changed and new data should be updated


The ES6 Way

To create a new object with the state in ES6 we can use the spread operator. Like this

...
case ActionType.SUCCESS_GET_DATA : {
    let newState = { ...state, [action.uniqueKey]: action.payload };
    return state.merge(newState);
}
...

I did the uniqueKey part as a variable because you will want a unique name for your state.

IMO this syntax is much easier to understand than the Object.assign

Immutable Update Patterns, Here's what an example of updating state.first.second[someId].fourth might look like: Copy Note that this is true for both arrays and objects, but nested values still must be Others, like immutability-helper (a fork of the now-deprecated React  In apps using React Redux the components are often separated into two categories, components and containers. This is to distinguish components that use the state tree and dispatch actions from dumb components that are only used for presentation. This app has three dumb components: App - The root of the app.


You can use Object.assign() function:

var state = {
    accessToken: null,
    isLoggedIn: false,
};

var user = {
    name: 'some name',
    email: 'some email'
};

var newState = Object.assign({}, state, {user});

console.log(newState);

Updating Normalized Data, One approach is to merge the contents of the action into the existing state. reducers, each slice reducer will need to know how to respond to this action appropriately. Update our Post object with a new "comments" array Because this will often involve more nested updates, you may want to use an immutable update  I have a connected React component which gets an array of Plot objects from state. It also gets several arrays of strings from state. Like this: function mapStateToProps(state) { return { plots: state.plots.plots, varietyFilter: state.plots.varietyFilter, regionFilter: state.plots.regionFilter, grow


First I see that your state is actually an array, but I think you would need an object right?

So it would be:

const initialState = {
    accessToken: null,
    isLoggedIn: false,
}

(requires Babel) So with spread operator you can:

return {
    ...initialState,
  user: {
    name: '...',
    surname: '...'
  }
};

Or if you do not transpile via Babel alike:

return Object.assign({}, initialState, {
    user: {
    name: '...',
    surname: '...'
  }
});

Replacing state in Redux reducers: a few approaches – Chariot , The Redux state management engine relies on returning new state object from LoDash Documentation - a custom merge strategy to concat arrays Note the use of an empty object in the first parameter of the Object.assign function. in props/state and Redux, and learning how to use the React Router. Redux: Prepend an item to an array (This isn’t specific to Redux – the same method applies with plain React state. See here for how to adapt it.) The mutable way to do this would be to use Array’s .unshift function to add an item to the front. Array.prototype.unshift mutates the array, though, and that’s not what we want to do.


Using ES6 spread syntax

...
case 'ACTION_TYPE_A': {
return { ...state, action.key: action.value };
}
...

This will return the merged state by updating the 'key' if it exists in the original state.

Merging and Deduplicating Data Arrays with Array.reduce, I'm currently working on a React/Redux project, and I'm faced with the task of a GET request to the API and return an array of projects all with {state: “New”}. mergeState change for nested Structure in React and Redux. setState is often nasty when you unfortunately have nested structure in your React/Redux state. This package makes setState easy with the nested Structure. Install. Just like other packages. npm i --save mergestate The s is lowercased due to my mistake and I cannot change the it. Sorry


Everything according to new Es6 format : )

A total addToDo reducer function where the data is appended to the previous state. And you get the output of a new state data : )

export const addToDo = (state, action) => {
const { name, email, phone, image,key } = action;
  var data = [...state.data];
  var newData = {
     name: name, email: email, phone: phone, image: image,key:key 
  }
   data.push(newData)

return(
state.merge({
  data : data
})

)};

Happy coding.

How to update nested props in reducer? · Issue #432 · reduxjs/redux , I can't figure out the correct way to update nested property in reducers state. When I write return in such was the "data" property is not merged. try to use this spread operator on the state it gives me the error, "object of type State is not an array type". exclude: [/node_modules/, /react-redux-firebase/], loader: "babel", query:  Only Return New Object References If Needed. React Redux does shallow comparisons to see if the mapStateToProps results have changed. It’s easy to accidentally return new object or array references every time, which would cause your component to re-render even if the data is actually the same.


Merging state with lodash · Issue #398 · reduxjs/redux · GitHub, This should work: _.merge({}, state, result.data) . If I've got an object which contains an array of key/value pairs, and I want to update the state  Simplifying Immutable Updates with Redux Starter Kit. Our Redux Starter Kit package includes a createReducer utility that uses Immer internally. Because of this, you can write reducers that appear to "mutate" state, but the updates are actually applied immutably. This allows immutable update logic to be written in a much simpler way.


Applying redux reducers to arrays, import React from 'react' import { connect } from 'react-redux' import on the state array creates a copy, with the counter at the given index  Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity:


Immutability in React and Redux: The Complete Guide, How To Update State in Redux When this notation is placed before an object or array, it unwraps the children Since React will shallow merge the object you pass into this. This is the state passed to your reducer the first time. When Redux initializes it dispatches a "dummy" action to fill the state. So your counter reducer was called with state equal to undefined. This is exactly the case that "activates" the default argument. Therefore, state is now 0 as per the default state value (state = 0).