Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Object passed into component.set is mutated by computed properties #479

Closed
Conduitry opened this issue Apr 13, 2017 · 2 comments
Closed

Comments

@Conduitry
Copy link
Member

REPL

<script>
	export default {
		computed: {
			b: a => a + 1
		},
		oncreate() {
			let obj = { a: 1 };
			this.set( obj );
			console.log( obj );
		}
	}
</script>

This logs { a: 1, b: 2 }.

I have an app where I have an array of different objects that I pass to component.set as appropriate. The computed property is getting assigned into the object that's passed in. Calling component.set again with a previously used (and mutated) object is a problem when dev mode is enabled, because attempting to set the read-only computed property throws an error.

@Conduitry
Copy link
Member Author

It looks like this is consciously being done in the recompute builder

const statement = `state.${key} = newState.${key} = ${generator.alias( 'template' )}.computed.${key}( ${deps.map( dep => `state.${dep}` ).join( ', ' )} );`;

so that other computed properties that depend on this computed property will be recomputed. I wonder if there's another way we could handle this that wouldn't be too complicated. I suppose we could always assign( {}, newState ) before we start mutating it.

@Rich-Harris
Copy link
Member

Best place to do that is probably inside set since this is presumably only ever going to be an issue with user-supplied objects, rather than ones generated for nested components:

function set( newState ) {
-  this._set( newState );
+  this._set( assign( {}, newState ) );
  ( this._root || this )._flush();
}

Though that raises an awkward problem — set then depends on assign. So I guess we need to get a bit more sophisticated about helpers depending on each other (which isn't the worst thing in the world). I'll open a separate issue for that.

Rich-Harris added a commit that referenced this issue Apr 14, 2017
Rich-Harris added a commit that referenced this issue Apr 14, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants