Ad

React-Redux: Infinite Loop When Concat To An Array In State?

So I am trying to add elements to an array I have stored in the state. I know you are not supposed to mutate the state directly, so I found that using concat is the best way of doing it.

However when I try doing this, I get an infinite loop.

reducer.js:

const initialState = {
  name : null, //puzzle name
  start : []
};

export default createReducer(initialState,{
  [START_PROCESS]: (state,payload) => {
    return Object.assign({},state,{
      start : state.start.concat(['test']);
    })
  }
});

the result is ['test','test','test','test'...

e.g:

  • setting start: state.start works
  • setting start: state.start + 'test' results in an infinite loop of testtesttest..

I don't know what causes this weird behavior. From what I know the state is only modified this way by creating a new state so there is no way it could feed back into itself.

createReducer.js

export function createReducer(initialState, reducerMap) {
    return (state = initialState, action) => {
        const reducer = reducerMap[action.type];

        return reducer
            ? reducer(state, action.payload)
            : state;
    };
}

startAction.js

const START_PROCESS = 'START_PROCESS';
export function startProcess(data) {
  return {
    type : START_PROCESS,
    payload : {
      data : data //where data is a string
    }
  }
}

viewAction.js

...
export default ProcessView extends React.Component {
  render() { return <div>{this.props.actions.startProcess('string')}</div> }
}
export default connect(mapStateToProps,mapDispatchToProps)(ProcessView)
Ad

Answer

The best way of avoiding state mutation is definitely with ImmutableJS. In your case I would say that maybe you call your action wrong. Are you sure it is not called inside render?

Ad
source: stackoverflow.com
Ad