mitosis
mitosis copied to clipboard
core: Can't assign "props" to "state"
we need a way to assign props to state
https://github.com/BuilderIO/mitosis/blob/main/docs/gotchas.md#cant-assign-params-to-state
we can either inject the workaround into onMount or for some generators
@decadef20 do you think we can gather all the props assignments in state and move them into onMount?
@decadef20 do you think we can gather all the
propsassignments instateand move them intoonMount?
Yeah. I agree with you. And doing a assignment in onMount is easy to understand.
One thing I've been thinking we need that would help this is something like an onInit hook, like something that lets you run code immediately, before mount, e.g. like
export default function MyComponent(props) {
const state = useState({ foo: null })
onInit(() => { state.foo = props.foo })
}
which then outputs to like ngOnInit for angular (or maybe constructor), created or beforeCreate for Vue, etc
I think onMount works in the meantime tho, some things occasionally may double render and it won't affect server side rendering, and we can add something like onInit (open to other names) for things that need to affect the server side / static render and ideally happen before render for other reasons
yeah maybe we should change onInit to work sooner for this case
actually if we just require this to happen in onInit then we can avoid all this. Ideally any prop on state can be refactored into onInit then when we generate the file the onInit code will be placed correctly
Oh funny I didn't realize we already had it, but yeah we can do all this setup in that if in the right place
Yeah I added it recently but it should definitely be used to set default values and nothing async
I moved OnInit to be sooner https://github.com/BuilderIO/mitosis/pull/377/commits/3ee7ae16dfe0fc073cb8e2d9244384deea7a3c89
I need a helper function to refactor any props on state to be in the onInit function
const state = useState({
myValue: prop.parentValue || 'defaultValue'
})
before we generate the component we should transfer any prop on state to onInit
const state = useState({
myValue: undefined
});
onInit(() => {
state.myValue = prop.parentValue || 'defaultValue';
})