Reputation: 12034
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 ?
Upvotes: 14
Views: 9371
Reputation: 1442
I think there are 3 ways to solve this:
localstore:
dispatching:
two-way-binding:
Upvotes: 4
Reputation: 3397
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>
! 😅Upvotes: 6