You're on the right track.
Store the stock prices as a hash in a writable()
store.
// in stores.js
export const stocks = writable({})
Then when you want to update the price or add a new stock, you call stocks.update()
.
// in stores.js
export function update(symbol, data) {
// using `...` to destructure a copy, we don't want to overwrite previous value
stocks.update(({...records}) => {
// now update the copy
records[symbol] = data
// return the new value for the store, this will trigger updates in templates that subscribe
return records
})
}
In your .svelte
component, import the store.js
<script>
import {stocks, update} from './store.js'
import {onMount} from 'svelte'
update('AAPL', {ask: 10, bid: 20})
update('MSFT', {ask: 10, bid: 20})
onMount(() => {
setTimeout(() => update('AAPL', {ask: 10.20, bid: 10.25}), 2000)
setTimeout(() => update('AAPL', {ask: 10.30, bid: 10.35}), 4000)
})
</script>
<!-- use dollar sign in front of store name to make svelte auto-subscribe -->
<pre>
{JSON.stringify($stocks, null, 2)}
</pre>