Context undefined when called from a function in onClick, but not if called in component
I have a component which has a button that onClick calls a function. That function tries to access a few contexts but they are all undefined. If I try to access the contexts from the caller component they work. Is there a specific reason why this happens? Any workarounds aside from passing down all the contexts to the function every time?
10 Replies
you can easily reproduce the issue here
Solid Playground
Quickly discover what the solid compiler will generate from your JSX template
the context is only visible inside children computations
where "inside" means you are executing code after the computation got called/refreshed, and before it ended
the onClick callback is executing at a later point in time, outside of any computations
so it sees no contexts
I don't know if there's a nice primitive in #solid-primitives for this, it could be interesting
you can solve your problem with
runWithOwner
ive never heard of that, is it documented somewhere?
SolidJS
Solid is a purely reactive library. It was designed from the ground up with a reactive core. It's influenced by reactive principles developed by previous libraries.
runWithOwner+getOwner and you can execute stuff inside whatever computation you can get yours hands on
so in this case the owner should be the parent component which is calling the function?
components are not really owners, owners are things like memos, effects and roots
getOwner gives you the current owner, so you can just call it inside your component
it works
I wonder if there is a way to abstract this from the caller
or does the component caller need to know to run it with runWithOwner every time?
It could be abstracted away at Solid's level, but it isn't free, so not worth it probably