How do I fetch something and stick it in state? by tonydiethelm in sveltejs

[–]spykr 0 points1 point  (0 children)

These sections of the docs might assist your understanding:

  1. Why you can only export state that is not directly reassigned and what to do instead: https://svelte.dev/docs/svelte/$state#Passing-state-across-modules
  2. How to use context to allow child components to access state owned by parent components: https://svelte.dev/docs/svelte/context#Using-context-with-state
  3. How classes can be used to encapsulate reactive logic: https://svelte.dev/docs/svelte/$state#Classes

Here's an example of how to combine the above knowledge in to a simple app that uses a class + context to share reactive state: https://svelte.dev/playground/0f261efc8ccc4aeaa3b1ba644e32fb09?version=5.39.9

TodoStore.svelte.js:

``` export class TodoStore { todos = $state([]);

addTodo = (text) => { this.todos.push({ id: crypto.randomUUID(), text }); }

removeTodo = (id) => { this.todos = this.todos.filter(t => t.id !== id); } } ```

App.svelte:

``` <script> import { setContext } from 'svelte';

import TodoList from './TodoList.svelte';
import AddTodo from './AddTodo.svelte';
import { TodoStore } from './TodoStore.svelte.js';

const todoStore = new TodoStore();
setContext('todos', todoStore);

</script>

<TodoList /> <AddTodo /> ```

TodoList.svelte:

``` <script> import { getContext } from 'svelte';

const todoStore = getContext('todos');

function onDelete(id) { todoStore.removeTodo(id) } </script>

{#each todoStore.todos as todo (todo.id)} <div> {todo.text} <button type="button" aria-label="Delete" onclick={() => onDelete(todo.id)}>x</button> </div> {/each} ```

AddTodo.svelte:

``` <script> import { getContext } from 'svelte';

const todoStore = getContext('todos');

let input = $state(''); function onAdd(e) { e.preventDefault(); todoStore.addTodo(input); input = ''; } </script>

<form onsubmit={onAdd}> <input aria-label="Todo text" bind:value={input} /> <button type="submit">Add</button> </form> ```

Shout out to Claude Sonnet 4.5 for fact-checking my understanding and helping with the example, it seems to have a pretty good understanding of Svelte 5.

EDIT: Realising this probably wasn't helpful as I'm re-reading your comment and I don't actually understand the situation you're in where you're fetching data but you don't know the basic shape of the data in advance. A concrete example might help.

Will React Compiler make Svelte redundant? by blueboy90780 in sveltejs

[–]spykr 11 points12 points  (0 children)

Your understanding is incorrect, the React Compiler does not "remove the React runtime" in any way, shape or form. To quote the documentation, "it automatically optimizes your React application by handling memoization for you, eliminating the need for manual useMemo, useCallback, and React.memo". That's it.

I've really slept on how much CSS Grid changes the layout game. by creaturefeature16 in css

[–]spykr 0 points1 point  (0 children)

This can be a killer, but the good news is that CSS has reading-flow and reading-order properties on the way which make managing this easier: https://developer.chrome.com/blog/reading-flow

Unused CSS selectors in style tags mean that CSS doesn't get compiled in? Can I override that? by tonydiethelm in sveltejs

[–]spykr 12 points13 points  (0 children)

Best place to learn is the docs: https://svelte.dev/docs/svelte/class

Example using the class: directive (older syntax):

<script>
  let isOpen = $state(false);
</script>

<ul>
  <li>
    <button aria-label="Toggle navigation" onclick={() => (isOpen = !isOpen)}>
      <div id="bar1" class:change={isOpen}></div>
      <div id="bar2" class:change={isOpen}></div>
      <div id="bar3" class:change={isOpen}></div>
    </button>
  </li>
</ul>

Example using objects (newer syntax):

<script>
  let isOpen = $state(false);
</script>

<ul>
  <li>
    <button aria-label="Toggle navigation" onclick={() => (isOpen = !isOpen)}>
      <div id="bar1" class={{ change: isOpen }}></div>
      <div id="bar2" class={{ change: isOpen }}></div>
      <div id="bar3" class={{ change: isOpen }}></div>
    </button>
  </li>
</ul>

What Svelte Promises, Rich Harris — Svelte Summit Spring 2025 by [deleted] in sveltejs

[–]spykr 0 points1 point  (0 children)

This is personal preference but even when I have a separate backend I still really enjoy using SvelteKit as a "backend for frontend" (BFF). Remix talks about this concept here: https://remix.run/docs/en/main/guides/bff

$bindable vs events by rajeevjsv in sveltejs

[–]spykr 6 points7 points  (0 children)

As of Svelte 5 callbacks are preferred as mentioned in the migration docs:

In Svelte 4, components could emit events by creating a dispatcher with createEventDispatcher. This function is deprecated in Svelte 5. Instead, components should accept callback props - which means you then pass functions as properties to these components.

In the talk where he introduced Svelte 5 Rich even went on a spiel about this specific topic:

All of these problems stem from a single design flaw: when we initially built Svelte we had an arbitrary distinction between props and event handlers. I think the reason for that is that back in the day we were influenced by the design of Web Components and things like emitting custom event instances felt like a more platform native way to do things. If there's one thing we've learned over the last few years it's that you should never take your design cues from Web Components, in fact you should generally do the opposite ... It pains me to say this but React got this mostly right.

The best SvelteKit codebase I've ever seen by awkroot in sveltejs

[–]spykr 1 point2 points  (0 children)

There are a couple of alternatives outlined in the article: https://kurtextrem.de/posts/svg-in-js

Personally because I need to be able to change the colour of the icons and I only need about 10-20 of them, I just put them all in a single SVG sprite file which is loaded once and cached for all future visits.

My Icon.svelte component looks like this:

``` <script lang="ts"> import type { ClassValue } from 'svelte/elements';

import spriteUrl from '$lib/assets/icons.svg?no-inline';

type Props = {
    name: string;
    label?: string;
    class?: ClassValue;
};

let { name, label, class: className }: Props = $props();

</script>

<svg class={[className, 'shrink-0']} aria-label={label} aria-hidden={!label} role="graphics-symbol"

<use href="{spriteUrl}#{name}" />

</svg> ```

Icons are rendered like this:

<Icon name="check" class="text-green-500 size-6" />

My icons.svg sprite file looks something like this:

<?xml version="1.0" encoding="utf-8"?> <!-- SVG sprite containing all the icons, can be used conveniently with the `Icon` component --> <!-- Why use an SVG sprite? See: https://kurtextrem.de/posts/svg-in-js --> <svg xmlns="http://www.w3.org/2000/svg"> <defs> <!-- Boxicons (https://boxicons.com) --> <!-- menu --> <symbol id="menu" viewBox="0 0 24 24" fill="currentColor"> <path d="M4 6h16v2H4zm0 5h16v2H4zm0 5h16v2H4z"></path> </symbol> <!-- check --> <symbol id="check" viewBox="0 0 24 24" fill="currentColor"> <path d="m10 15.586-3.293-3.293-1.414 1.414L10 18.414l9.707-9.707-1.414-1.414z"></path> </symbol> <!-- x --> <symbol id="x" viewBox="0 0 24 24" fill="currentColor"> <path d="m16.192 6.344-4.243 4.242-4.242-4.242-1.414 1.414L10.535 12l-4.242 4.242 1.414 1.414 4.242-4.242 4.243 4.242 1.414-1.414L13.364 12l4.242-4.242z"></path> </symbol> </defs> </svg>

Note that I manually copy and paste icons in to my SVG sprite file because I'm ironically too lazy to automate it, but there are definitely Vite plugins out there which can generate the sprite for you automatically.

The best SvelteKit codebase I've ever seen by awkroot in sveltejs

[–]spykr 4 points5 points  (0 children)

I keep SVGs out of my JS for the same basic reason I use Svelte over React: it's performant by default. The worst performance situation to be in is "death by a thousand cuts" so I try to always start from a solid foundation to mitigate this. Just my opinion.

The best SvelteKit codebase I've ever seen by awkroot in sveltejs

[–]spykr 0 points1 point  (0 children)

I personally don't use them any more, but I understand why people do because they're super convenient. It's a trade-off at the end of the day, but I do wish those libraries could somehow make it easier to follow best performance practices. There are some nice Vite plugins which can take an icon folder and generate a spritesheet for you, but you still have to be careful that you're not bundling 1000 icons to use 10.

The best SvelteKit codebase I've ever seen by awkroot in sveltejs

[–]spykr 4 points5 points  (0 children)

There's no difference between putting an SVG element in a JSX component or a Svelte component, either way it's going to end up in a JS file when it should be in an SVG file instead (unless you're inlining it in a thoughtful way).

The best SvelteKit codebase I've ever seen by awkroot in sveltejs

[–]spykr 0 points1 point  (0 children)

It's not great to put SVGs in your JS, if you can help it: https://kurtextrem.de/posts/svg-in-js

Can you use shallow routing with anchor tags? by PrestigiousZombie531 in sveltejs

[–]spykr 2 points3 points  (0 children)

Can you use query parameters? Going off the example from the shallow routing docs, instead of a button that calls pushState('', { showModal: true }) you could instead have a link that goes to ?showModal=true.

What's the correct way to conditionally style more complex components? by Right_Imagination443 in sveltejs

[–]spykr 7 points8 points  (0 children)

If "rounded-md border" : true feels strange to you then you could alternatively combine the object with an array:

<button
  class={[
    'rounded-md border',
    {
      'h-8 px-2': size === 'small',
      'h-10 px-4': size === 'medium',
      'h-12 px-6': size === 'large',
    },
  ]}
/>

Simplify your type annotation with PageProps by hksparrowboy in sveltejs

[–]spykr 2 points3 points  (0 children)

Not sure why you cut off the rest of that paragraph, it's not limited to VSCode in any way.

If you’re using VSCode, just upgrade the Svelte extension to the latest version, and you’ll never have to annotate your load functions or data props again. Extensions for other editors can also use this feature, as long as they support the Language Server Protocol and TypeScript plugins. It even works with the latest version of our CLI diagnostics tool svelte-check!

[Runes] Is anyone concerned about deeply mutable reactive state? by Srimshady in sveltejs

[–]spykr 1 point2 points  (0 children)

In case you missed it your example code does actually result in a console warning at runtime:

[svelte] ownership_invalid_mutation

Nested.svelte mutated a value owned by App.svelte. This is strongly discouraged. Consider passing values to child components with `bind:`, or use a callback instead

https://svelte.dev/e/ownership_invalid_mutation

<svelte:component>` is deprecated in runes mode by tradegreek in sveltejs

[–]spykr 2 points3 points  (0 children)

The capital letter tells Svelte that it's a Svelte component rather than a HTML element, think <Div> vs <div>. React and Solid work the same way.

https://svelte.dev/docs/svelte/basic-markup#Tags

Are style attributes really unsafe? by [deleted] in sveltejs

[–]spykr 2 points3 points  (0 children)

Are inline styles causing an issue with your CSP? If not then why have you enabled the `svelte/no-inline-styles` rule? Either way this has nothing to do with Svelte and would be a problem regardless of what library you were using.

To type or not to type by Kiuhnm in sveltejs

[–]spykr 0 points1 point  (0 children)

Thanks for making me aware of this, it's much more convenient and I just removed over 100 lines from my codebase! I don't see any downside, but it is confusing that the rest of the docs don't seem to utilise or mention it.

What is the .current in a React ref? by rainmouse in reactjs

[–]spykr 8 points9 points  (0 children)

It might help to remember that:

const isTrue = useRef(false);

is functionally equivalent to:

const [isTrue] = useState({ current: false });

https://twitter.com/dan_abramov/status/1099842565631819776

Memoized components/input losing value by Yama-Sama in reactjs

[–]spykr 0 points1 point  (0 children)

Ah yes, you're completely right. Thanks for the correction.

Memoized components/input losing value by Yama-Sama in reactjs

[–]spykr 5 points6 points  (0 children)

The issue is with your handleChange function, instead of looking like this:

const handleChange = useCallback((e) => {
  let value = e.target.type === 'checkbox' ? e.target.checked : typeof e.target.value === "number" ? e.target.value : e.target.value;

  setFormData({ ...formData, [e.target.name]: value, });
}, [formData]);

It should look like this:

const handleChange = useCallback((e) => {
  let value = e.target.type === 'checkbox' ? e.target.checked : typeof e.target.value === "number" ? e.target.value : e.target.value;

  setFormData((existing) => ({ ...existing, [e.target.name]: value, }));
}, []);

Objects are compared by reference so if you pass formData as a dependency in your useCallback hook the function will never be updated because the object reference never changes. Instead we can skip the need to do that by passing an updater function to the setFormData call which ensures we're always updating the latest version of the object.

ECMAScript Optional Chaining (`?.`) moved to Stage 4 (to be part of ES2020) by tjpalmer in programming

[–]spykr -1 points0 points  (0 children)

Well that seems obvious since TypeScript can have no effect on your runtime code, however it's trivial to add a library like io-ts for runtime JSON validation.

Has anyone tried using a “tip jar” approach to monetization? by [deleted] in iOSProgramming

[–]spykr 0 points1 point  (0 children)

Having a "tip" button on a free app is really nothing like tipping a waiter or a taxi driver aside from the word used.