Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

session store #4

Open
david-plugge opened this issue Sep 11, 2022 · 0 comments
Open

session store #4

david-plugge opened this issue Sep 11, 2022 · 0 comments

Comments

@david-plugge
Copy link
Owner

david-plugge commented Sep 11, 2022

I just leave this here for now

/src/lib/helper.ts

import { derived, type Readable } from 'svelte/store';

export function dedupeDerived<T, R>(
	store: Readable<T>,
	fn: (data: T) => R = (data) => data as unknown as R
): Readable<R> {
	let value: R;
	return derived(store, (data, set) => {
		const newValue = fn(data);
		if (value !== newValue) {
			value = newValue;
			set(value);
		}
	});
}

/src/lib/stores.ts

import { getContext } from 'svelte';
import type { Readable } from 'svelte/store';

// App.SupabaseSession = Session interface

export const session: Readable<App.SupabaseSession> = {
	subscribe(run, invalidate?) {
		const store = getContext<typeof session>('__SESSION__');
		return store.subscribe(run, invalidate);
	}
};

/src/routes/+layout.svelte

<script lang="ts">
	import { page } from '$app/stores';
	import { setContext } from 'svelte';
	import { dedupeDerived } from '$lib/helper';

    // we can´t use the imported session here
	const session = setContext(
		'__SESSION_',
		dedupeDerived(page, ($page) => $page.data.session)
	);
</script>

{#if $session.user}
	<a href="/account">Account</a>
{:else}
	<a href="/signin">Sign in</a>
{/if}

<slot />

/src/routes/+page.svelte

<script lang="ts">
	import { session } from '$lib/stores';
</script>

<pre>{JSON.stringify($session.user, null, 2)}</pre>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant