Yield Destructured Variables
Hi everyone.
Glad to being here for writing about a proposal for improving Javascript development experience.
Refer to https://tc39.es/ecma262/#sec-generator-function-definitions, with generator functions, we can taking advantages of yield statement which returns as an intermediate value.
IMHO, one thing miss with generator functions : yield destructured variables.
Let me explain my proposal and give you the context of this need :
In the new Vue 3, there is a new concept called Composition API which looks like React hooks.
This new concept answers many reusable and robustness problematics : typings improved, seperation of concern, and centralization of treatments.
One snippet of code is worth a thousand words :
import { reactive } from "vue";
// feature.js
export function useFeature() {
const state = reactive({
id: 0,
})
const setId = (id) => (state.id = id)
return {
id: state.id,
setId,
}
}
// component.js
function setup() {
const { id, setId } = useFeature()
const name = ref("foo")
return {
id,
setId,
name,
};
}
An example of Composition API
Return object of setup function in a component expose a Render Context which is transmitted to the template or JSX.
What you can see, useFeature
expose two fields, and we have to get them and return them to the Render Context.
With yield values, we could almost simplify it (if let's say Vue permits setup
as a generator function and takes yield values incrementally) :
// component.js
function* setup() {
const { id, setId } = useFeature()
yield { id, setId }
const name = ref("foo")
return {
name,
}
}
As you can see, useFeature fields have to be yield separately.
Here my proposal, with this context :
// component.js
function* setup() {
yield ({ id, setId } = useFeature())
const name = ref("foo")
return {
name,
};
}