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

Transactions #1535

Closed
btakita opened this issue Jun 9, 2018 · 4 comments
Closed

Transactions #1535

btakita opened this issue Jun 9, 2018 · 4 comments

Comments

@btakita
Copy link
Contributor

btakita commented Jun 9, 2018

Calling set multiple times from different helper functions can cause undesired interstitial state.

Transactions would allow these set calls to be consolidated into a single set.

Here is one potential syntax:

function helper(store) {
  store.set({ team: 'blue' })
}
async function fetch__something() {
  return 'big'
}
await store.transaction(async () => {
  helper(store)
  store.set({ something: await fetch__something() })
  store.set({ foo: 'bar' })
})
@btakita
Copy link
Contributor Author

btakita commented Jun 9, 2018

Here's an implementation that I have been using:

const { assign } = Object
const clone = (...args) => assign({}, ...args)
function mixin(target, ...sources) {
	for (let i=0; i < sources.length; i++) {
		const source = sources[i]
		const propertyNames = Object.getOwnPropertyNames(source)
		for (let j=0; j < propertyNames.length; j++) {
			const propertyName = propertyNames[j]
			Object.defineProperty(
				target,
				propertyName,
				Object.getOwnPropertyDescriptor(source, propertyName))
		}
	}
	return target
}
Store.prototype.transaction = async transaction(fn) {
	const store__transaction = mixin(new Store(), this)
	store__transaction._state = clone(this._state)
	store__transaction._computed = clone(this._computed)
	const __set = {}
	store__transaction.set = __set__ => {
		assign(__set, __set__)
		assign(store__transaction._state, __set__)
	}
	store__transaction._state = clone(store__transaction._state)
	await Promise.all([fn(store__transaction)])
	this.set(__set)
	return store__transaction
}

@btakita
Copy link
Contributor Author

btakita commented Jun 12, 2018

A better implementation may depend on #1435

@btakita
Copy link
Contributor Author

btakita commented Jun 17, 2018

#1520

@Conduitry
Copy link
Member

This is addressed on components in v3 by having updates scheduled asynchronously in the next microtask.

There's no longer a single central store, so I don't think we want to encourage having some way to have atomic updates there.

Closing.

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