top | item 30510644

(no title)

ryansolid | 4 years ago

What does a reusable (ie import from another file) `useAutoCounter` look like in Svelte?

discuss

order

alskdjflaskjdhf|4 years ago

Probably the equivalent would be a custom store, something like this:

  <script>
    import { writable } from "svelte/store";
  
    function autoCounter(interval, initialValue = 0) {
      let { subscribe, update } = writable(initialValue);
      setInterval(() => update((n) => n + 1), interval);
      return { subscribe }
    }
  
    let counter = autoCounter(1000);
  </script>
  
  <div>The count is: {$counter}</div>

ryansolid|4 years ago

Yep. Looks sort of like the Solid example in the article. It's basically my auto-response to Svelte syntax. Once you do anything in Svelte it is more or less the same thing.

Just different priorities. In Solid you can take that code as is in the component and hoist it out to a function above and presto.. store. It's all the same thing everywhere. Same patterns, same usage, same building blocks. No new APIs, no new syntax.

It is nice when first learning not to worry about Svelte Stores and use the convenient syntax. It is also nice to learn something once and use it everywhere.