sveltejs / svelte

Cybernetically enhanced web apps
https://svelte.dev
MIT License
78.39k stars 4.1k forks source link

subscribe bind component #3592

Closed lagden closed 4 years ago

lagden commented 4 years ago

Hi!

I am trying to mask an entry using store.subscribe

If I use a simple input with bind:value, it works like a charm! But via component nope!!

Help!!

Example: https://svelte.dev/repl/9bb136ad545e479ab190cd7da1f6074f?version=3.12.1

Conduitry commented 4 years ago

When I first looked at this issue, I didn't notice that it involved mutating the value of a store in a subscription callback to the store. I'm surprised that this even works to the extent that it does, and I don't think this should be the right way to handle this.

What I would think would be the right way would be to write a custom store with an overridden set method which instead sets the store to the masked version of the string.

App.svelte

<script>
    import { smart } from './store.js';
</script>

<input bind:value={$smart}>
{$smart}

store.js

import { writable } from 'svelte/store';
import Mask from '@tadashi/mask/src';

const { set, subscribe } = writable();

export const smart = {
    set: value => set(Mask.masking(value, '+99 99 9-9999-9999')),
    subscribe
};

smart.set('5511978990935');

However, this has some janky behavior. The question, then, is whether two-way binding should be expected to work with stores whose set method doesn't actually set the store to that value, and I don't know the answer to that.

lagden commented 4 years ago

@Conduitry

That janky behavior is saving the day!

I did some modification in REPL, but I'm still using subscribe and wrote a custom store like you said above.

To avoid subscribe problems (I don't know if really happens), I always call the unsubscribe when the parent component is destroyed.

const unMask = creditCard.mask()
onDestroy(() => {
  unMask()
})

Thanks for the review.

antony commented 4 years ago

@Conduitry Is there an issue we want to fix here? I think this issue is pitched as a usage question which appears to be resolved (and the REPL is gone), and there might be a new issue regarding the (unusual) way stores are used which could be raised if you think it's worthwhile.

https://svelte.dev/repl/c2f16a288fa145c082810b2a2b6e6dd1?version=3