yarek
yarek

Reputation: 12034

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 ?

Upvotes: 14

Views: 9371

Answers (3)

nologin
nologin

Reputation: 1442

I think there are 3 ways to solve this:

localstore:

dispatching:

  • as you are doing currently ;)

two-way-binding:

Upvotes: 4

parker_codes
parker_codes

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:

  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.

Upvotes: 6

Shoejep
Shoejep

Reputation: 4839

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

Upvotes: 22

Related Questions