Skip to content Skip to sidebar Skip to footer

Redux State Is Being Edited Without Dispatching Any Action

I have an app with react + redux, and the problem is happening in the editing form. Description of the issue click 'edit' to edit a document Show the edit form I edit/delete one o

Solution 1:

This is why suggested method to deal with redux is ImmutableJS or immutable-helper or the kind.

It is very easy to make mistakes otherwise.

Here is what happend:

// constructor
this.state = {
  portlet: this.props.portlet,  // you put props in the state
}

// change handler
let editedDoc = Object.assign({}, this.state.portlet);
// here a new object is created, but if the value is not primitive, it is by reference.
// this means, while editedDoc and this.state.portlet are different objects, "_key"'s value is shared between these object.

And this is a mistake I have seen many people making. Also, it is a pain to debug such cases. So please use a helper library.

If you insist on using es6 to construct new object, it could get ugly as the nesting increases.

// example 1
_updatePortletKey(event) {
  const field = event.target.name;

  this.setState({
    portlet: {
      ...this.state.portlet,
      _keys: this.state.portlet._keys.reduce((agg, el) => {
        const key = Object.keys(el); 
        // btw, what are you trying to do here !! (my logic might be slightly off, as I didn't fully understood the transformation, but you get the idea, right?)
        if(key[0] === field) { 
          return [...agg, {...el, [field]: event.target.value}]
        }
        return [...agg,el]
      }, [])
    }
  })

Post a Comment for "Redux State Is Being Edited Without Dispatching Any Action"