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 ?
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
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:
<login>! 😅If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With