markjaquith / clerk-sveltekit

Clerk adapter for SvelteKit
Other
146 stars 21 forks source link

`initializeClerkClient` should be awaited #46

Open charisra opened 8 months ago

charisra commented 8 months ago

initializeClerkClient returns a Promise. So, shouldn't it be awaited? If so, you should fix both your documentation & examples. I noticed that without it, if I try to use window.Clerk inside a component's <script /> it errors because window.Clerk is undefined (yet). After adding await on initializeClerkClient it works.

thebrianbug commented 6 months ago

Having a top-level await can be tricky and not supported in older environments. How to account for those that can't support that?

Upon testing - if we block the thread here it may never resolve. I think this is the right place to start initializing Clerk, but I don't think the promise can ever finish until after it renders the page DOM. Blocking here may break the load.

charisra commented 6 months ago

Having a top-level await can be tricky and not supported in older environments. How to account for those that can't support that?

I mean I'm just stating the problem, not sure what the best solution would be. But I guess you can detect if the env is old/doesn't support await, e.g.:

if (!Promise.prototype.hasOwnProperty('finally')) {
    console.log('Async/Await not supported');
    // Provide alternative code paths here for older environments
} else {
    console.log('Async/Await supported');
    // Use async/await syntax
}

and use .then with a callback if it's an old env, e.g.:

// Alternative code path for older environments
function fetchDataOld() {
    return new Promise((resolve, reject) => {
        // Simulate an asynchronous operation
        setTimeout(() => {
            resolve('Data from older environment');
        }, 1000);
    });
}

// Usage in older environments
fetchDataOld().then(data => {
    console.log(data);
});
wobsoriano commented 2 months ago

When this PR gets merged, the initializeClerkClient will be deprecated. You need to use the <ClerkProvider> in your root layout and you can just subscribe to the exported stores anywhere in your components:

<script lang="ts">
    import { useClerkContext } from 'clerk-sveltekit/client'

        const { user, session, organization, clerk, client } = useClerkContext()

    $: {
       console.log('user', $user)
           console.log('session', $session)
           console.log('organization', $organization)
           console.log('clerk', $clerk)
           console.log('client', $client)
    }
</script>