Skip to content

Commit

Permalink
♻️ Extract store to its own file
Browse files Browse the repository at this point in the history
  • Loading branch information
Bernardstanislas committed Mar 23, 2023
1 parent f41458d commit 2d5de6b
Show file tree
Hide file tree
Showing 5 changed files with 16 additions and 23 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@ node_modules
!.env.example
vite.config.js.timestamp-*
vite.config.ts.timestamp-*
.vercel
13 changes: 13 additions & 0 deletions src/lib/stores/journal.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { browser } from '$app/environment';
import { writable } from 'svelte/store';

const JOURNAL = 'journal';

const storedJournal = browser ? window.localStorage.getItem(JOURNAL) : '';

export const journal = writable(storedJournal || '');
journal.subscribe((value) => {
if (browser) {
localStorage.setItem(JOURNAL, value);
}
});
4 changes: 1 addition & 3 deletions src/lib/word-counter.svelte
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
<script lang="ts">
import { getContext } from 'svelte';
import { JOURNAL } from '../routes/+layout.svelte';
import { journal } from '$lib/stores/journal';
let journal: SvelteStore<string> = getContext(JOURNAL);
$: count = $journal.split(' ').filter((value) => !!value).length;
</script>

Expand Down
17 changes: 0 additions & 17 deletions src/routes/+layout.svelte
Original file line number Diff line number Diff line change
@@ -1,22 +1,5 @@
<script context="module">
export const JOURNAL = 'journal';
</script>

<script lang="ts">
import { browser } from '$app/environment';
import { setContext } from 'svelte';
import { writable } from 'svelte/store';
import WordCounter from '../lib/word-counter.svelte';
const storedJournal = browser ? window.localStorage.getItem(JOURNAL) : '';
const journal = writable(storedJournal || '');
journal.subscribe((value) => {
if (browser) {
localStorage.setItem(JOURNAL, value);
}
});
setContext(JOURNAL, journal);
</script>

<slot />
Expand Down
4 changes: 1 addition & 3 deletions src/routes/+page.svelte
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
<script lang="ts">
import { getContext } from 'svelte';
import { JOURNAL } from './+layout.svelte';
import { journal } from '$lib/stores/journal';
let journal: SvelteStore<string> = getContext(JOURNAL);
$: encryptedJournal = $journal.length;
</script>

Expand Down

1 comment on commit 2d5de6b

@vercel
Copy link

@vercel vercel bot commented on 2d5de6b Mar 23, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.