mitosis icon indicating copy to clipboard operation
mitosis copied to clipboard

core: Can't assign "props" to "state"

Open PatrickJS opened this issue 3 years ago • 8 comments

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

PatrickJS avatar May 23 '22 13:05 PatrickJS

@decadef20 do you think we can gather all the props assignments in state and move them into onMount?

PatrickJS avatar May 24 '22 13:05 PatrickJS

@decadef20 do you think we can gather all the props assignments in state and move them into onMount?

Yeah. I agree with you. And doing a assignment in onMount is easy to understand.

decadef20 avatar May 24 '22 14:05 decadef20

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

steve8708 avatar May 24 '22 14:05 steve8708

yeah maybe we should change onInit to work sooner for this case

PatrickJS avatar May 24 '22 18:05 PatrickJS

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

PatrickJS avatar May 24 '22 18:05 PatrickJS

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

steve8708 avatar May 24 '22 18:05 steve8708

Yeah I added it recently but it should definitely be used to set default values and nothing async

PatrickJS avatar May 24 '22 18:05 PatrickJS

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';
})

PatrickJS avatar May 25 '22 13:05 PatrickJS