Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I append data without mutating state

Tags:

reactjs

redux

I'm creating a pagination system.
The reducer part looks like this:

(state, payload)=> {
            if (state.venues === null) {
                    state.venues = [];
            }
            state.venues.push.apply(state.venues, payload.data)
            return {
                    ...state,
                    isRequesting: false,
                    hasVenues: true,
                    venues: state.venues,
                    hasMessage: false
            }
    },

I iterate through state.venues in component.
The problem is, for the first request, state.venues is null so I should convert it to empty array to append payload to it.
But with this approach I think I mutate the state which is no allowed(recommend) in redux.
So how do can I achieve this without state mutation?

like image 785
Mehrdad Shokri Avatar asked Sep 03 '25 03:09

Mehrdad Shokri


2 Answers

To create a new array of venues use the spread operator:

var newVenues = [
    ...state.venues,
  'Tokyo'
];

You can use Object.assign to avoid mutating the state:

var newState = Object.assign({}, state, { venues: newVenues });

(I've left out the other parts of the state in your example for clarity).

like image 155
Mark Williams Avatar answered Sep 05 '25 00:09

Mark Williams


you can replace push with concat

concat is Array's pure function returns new array without mutating original values

  (state, payload) => {
    if (state.venues === null) {
      state.venues = [];
    }
    const newVenues = state.venues.concat(payload.data)
    return {
      ...state,
      isRequesting: false,
      hasVenues: true,
      venues: newVenues,
      hasMessage: false
    }
  }

BTW:

if you find yourself repeatedly using Object spread or Object.assign in every sub-reducer / nested state. you should consider using Immutable.js

like image 28
aifarfa Avatar answered Sep 05 '25 01:09

aifarfa