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

docs: Setting up client global state #13000

Open
sacrosanctic opened this issue Nov 14, 2024 · 0 comments
Open

docs: Setting up client global state #13000

sacrosanctic opened this issue Nov 14, 2024 · 0 comments
Labels
documentation Improvements or additions to documentation

Comments

@sacrosanctic
Copy link
Contributor

sacrosanctic commented Nov 14, 2024

Describe the bug

Setting up client global state is a footgun. (see #4339). Almost 3 years and users are still confused about how to do it safely. I want to add this pattern to the docs. This should also help clear up confusion around server shared state.

On top of that, it resolves optimistic UI issues mentioned in #12999.

// ReactiveState.svelte.js
export class ReactiveState {
    value = $state();

    constructor(initialValue) {
        this.value = initialValue
    }
}
// routes/+layout.js
export const load = () => {
	const randomNumber = Math.floor( Math.random() * 11)

	return { state: new ReactiveState(randomNumber) }
}
<script>
// +page.svelte
	let { data } = $props()
</script>

{data.foo.value}

<button onclick={() => { data.foo.value++ }}>add one</button>

repl: https://www.sveltelab.dev/90t6s7u8l5svxn0

Alternatives

There is an alternative which involves defining your own context.
https://discord.com/channels/457912077277855764/1303014718268637264
https://discord.com/channels/457912077277855764/1303116841895333918
https://discord.com/channels/457912077277855764/1301456686963359795

Severity

annoyance

Additional Information

Prior discussions

https://discord.com/channels/457912077277855764/1305894527738974258

Use cases

websocket updates
https://discord.com/channels/457912077277855764/1306898519184904235

persistent state across pages
https://discord.com/channels/457912077277855764/1307335664743747614

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
documentation Improvements or additions to documentation
Projects
None yet
Development

No branches or pull requests

2 participants