user1941583
user1941583

Reputation: 851

Svelte bind parent store from child

Can I use bind directive inside a child component, If the variable I'm binding to is a parent's store? How this relates to lifecycle events? As long as child's onMount triggers before parent's onMount (at least when I create a tree of new components at once), if bind is successful, but variable starts with null, do I get reactivity or not?

Upvotes: 0

Views: 890

Answers (2)

user1941583
user1941583

Reputation: 851

No need to bind to a parent store, if reactivity is what you want. Binds are reactive by default. So when you bind a child variable to a parent variable, you get the child one updated whenever the parent one changes. Per the relation to lifecycle events, considering that in the scenario you provide, parent-child couple is instantiated as a whole (i.e. the parent is not already mounted), what child sees from the parent variable depends on how it is declared and how, if any, it is updated with any of the available lifecycle events and/or it is read from any of the lifecycle events. Rest assured the order:

  • parent beforeUpdate
  • parent afterUpdate
  • child beforeUpdate
  • child afterUpdate
  • child onMount
  • parent onMount

Thanks to everyone for taking time to reply and provide a repl, Hope this answer gets agreement.

Thanks.

Upvotes: 0

kevinak
kevinak

Reputation: 126

Assuming I understand your question, this is possible: https://svelte.dev/repl/0bf7acc3bde9496d930795da34fae251?version=3.18.2

Unsure what you mean by lifecycle methods?

Upvotes: 0

Related Questions