Svelte: How to manually stop subscribe?

Viewed 1222

I have a store that fetches data once in a while – according to user's actions. This is a store because its data is used globally and mainly all components needs the latest data available.

But, for one specific component, I only need the first data loaded.

For this component, there is no reason to keep a subscribe() function running after the first fetch. So, how can I stop this subscribe function?

The only example in Svelte doc's uses onDestroy(), but I need to manually stop this subscribe().

I tried with a simple "count" (if count > 1, unsubscribe), but it doesn't work.

    import user from './store'
    
    let usersLoaded = 0
    
    const unsubscribe = user.subscribe(async (data) => {
        if(data.first_name !== null) {
            usersLoaded = usersLoaded + 1
        }
        
        if(usersLoaded > 1) {
            unsubscribe;
        }
    });

Here's a full working REPL:

→ https://svelte.dev/repl/95277204f8714b4b8d7f72b51da45e67?version=3.35.0

3 Answers

You might try Svelte's get. A subscription is meant for situations where you need to react to changes; it's a long-term relationship. If you just need the current value of the store, get is the way to go.

Occasionally, you may need to retrieve the value of a store to which you're not subscribed. get allows you to do so.

import { get } from 'svelte/store';

const value = get(store);

You can use auto subscribe: $user which will also auto unsubscribe. Some more details in the docs.

Example:

let user1 = null;
$: if ($user?.first_name && !user1) {
    user1 = $user.first_name;
    console.log('first user', $user.first_name);
}  

And you do not really need a writable store here. You can use a readable and use the set method to handle the fetch.

Something like:

const user = readable(defaultUser, set => {
   .... fetch the data ....
   .... set(data)
}

By the way: This is already async code and you can use set(data) to store the fetch result.

Related