Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

svelte: how can a component modify a variable/object on its parent?

I have a main application that contains the user object and the login component

<script>
let user = {}
</script>

hello {user.username}
<login user={user} />

In the login component, I make a call to ajax and receive some data like:

user = {id:1, username:"john"}

How can I then "inform" the main application I have updated the user so it displays hello john

For now, I dispatch an event

import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();

Is there a better way to achieve that ?

like image 570
yarek Avatar asked Jan 22 '26 01:01

yarek


2 Answers

In Svelte you can bind values to a component, so that when the child component updates, it also updates the parent.

You just need to change

<login user={user} />

to

<login bind:user={user} />

Here's a demo

like image 169
Shoejep Avatar answered Jan 25 '26 09:01

Shoejep


Svelte has 2-way binding via the bind keyword. You may have seen it when binding form inputs, and it works the same way in your own parent-child relationships.

Here's how it looks: <Login bind:user={user} /> or the shorthand when the names are the same: <Login bind:user />.

All you have to do is define a prop in the child (Login) component and when you update it, the parent value changes.

Here is a REPL to see it in action


Some extra things I'll point out in case you're interested:

  1. Components usually start with a capital letter. This allows the compiler to differentiate them with regular HTML components. Who knows, someday there may be an HTML component named <login>! 😅
  2. While the strategy above works for user logins, the typical way to handle this is using the concept of stores.
like image 39
parker_codes Avatar answered Jan 25 '26 08:01

parker_codes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!