Cookie Consent by Free Privacy Policy Generator 📌 Using Sharable Runes with TypeScript in Svelte5


✅ Using Sharable Runes with TypeScript in Svelte5


💡 Newskategorie: Programmierung
🔗 Quelle: dev.to

I don't know about you, but I don't like using Runes with $state in Svelte 5. Sure, they're easier to set data in your component, but I don't write code and manually put getters and setters.

Single Responsibility Principle

I don't write state inside my component except in small apps. I like to create reusable shared hooks. If it can't be shared, it is still better to follow the SRP for clean coding techniques.

rune.svelte.ts

First, I created a rune that works like Nuxt or Qwik Signals. I don't want to call the variable as a function, and I don't want to call set. The value attribute is the best implementation. You can create your own if you disagree.

export const rune = <T>(initialValue: T) => {

    let _rune = $state(initialValue);

    return {
        get value() {
            return _rune;
        },
        set value(v: T) {
            _rune = v;
        }
    };
};

This is what I use instead of $state everywhere in my app, with the exception of small changes in a component.

Shared Store

If you follow my posts, than you've seen a version of my shared store. It can be done with Runes as well.

import { getContext, hasContext, setContext } from "svelte";
import { readable, writable } from "svelte/store";
import { rune } from "./rune.svelte";

export const useSharedStore = <T, A>(
    name: string,
    fn: (value?: A) => T,
    defaultValue?: A,
) => {
    if (hasContext(name)) {
        return getContext<T>(name);
    }
    const _value = fn(defaultValue);
    setContext(name, _value);
    return _value;
};

// writable store context
export const useWritable = <T>(name: string, value?: T) =>
    useSharedStore(name, writable, value);

// readable store context
export const useReadable = <T>(name: string, value: T) =>
    useSharedStore(name, readable, value);

// shared rune
export const useRune = <T>(name: string, value: T) =>
    useSharedStore(name, rune, value);

Using this method, you can call useRune in you app for shared state anywhere.

Component 1

const user = useRune('user', { ...user state });

Component 2

const user = useRune('user');

And it will just work!

Custom Runes

You can do the same thing with custom Runes. Let's say I want to keep track of the Firebase user's state, and I want to share it across my app. I don't want to keep calling onIdTokenChanged. I can simply created a shared hook.

const _useUser = (defaultUser: UserType | null = null) => {

    const user = rune(defaultUser);

    const unsubscribe = onIdTokenChanged(
        auth,
        (_user: User | null) => {
            if (!_user) {
                user.value = null;
                return;
            }
            const { displayName, photoURL, uid, email } = _user;
            user.value = { displayName, photoURL, uid, email };
        });

    onDestroy(unsubscribe);

    return user;
};

export const useUser = (defaultUser: UserType | null = null) =>
    useSharedStore('user', _useUser, defaultUser);

Now I can use:

const user = useUser();

Anywhere in my app (hooks or components!), and is SAFE for the server. I believe this should be built into Svelte (and all Frameworks). The closest thing I have seen is useState() in Nuxt --- not to be confused with React.

Hope this helps those that are migrating to Svelte 5. I will be updating my SvelteKit Firebase Todo App article in the coming weeks.

J

See Also:

  • Code.Build - Finishing Firebase Course
  • Newsletter - Subscribe for more Svelte 5 and Firebase tips!
...

✅ Using Sharable Runes with TypeScript in Svelte5


📈 119.09 Punkte

✅ My first Svelte5 reactive component


📈 34.67 Punkte

✅ Exploring the magic of runes in Svelte 5


📈 31.22 Punkte

✅ NFT 101: The Comprehensive Guide to Runestone & Runes Protocol


📈 31.22 Punkte

✅ All you need to know about runes and runewords in Diablo 2: Resurrected


📈 31.22 Punkte

✅ How Types Work in TypeScript – Explained with JavaScript + TypeScript Code


📈 20.73 Punkte

✅ I made "TypeScript Swagger Editor", new type of Swagger UI writing TypeScript code in the browser


📈 20.73 Punkte

✅ 10 typescript developers you must follow to become typescript expert in 2024


📈 20.73 Punkte

✅ Getting Started with TypeScript: A Quick Introduction From JavaScript to TypeScript!


📈 20.73 Punkte

✅ Introduction to TypeScript — What is TypeScript?


📈 20.73 Punkte

✅ Using Vue.js with TypeScript: Boost Your Code Quality


📈 14.9 Punkte

✅ Create a Headless CMS Using OceanBase and TypeScript: A Step-By-Step Tutorial


📈 14.9 Punkte

✅ Getting started with React.js with Typescript using vite.js⚡


📈 14.9 Punkte

✅ Bundle and Publish TypeScript Package using Rollup


📈 14.9 Punkte

✅ You can’t run away from runtime errors using TypeScript


📈 14.9 Punkte

✅ Using Apache ECharts with Lit and TypeScript


📈 14.9 Punkte

✅ Build Expense Manager App Using React And TypeScript


📈 14.9 Punkte

✅ How to Persist User Info Using Redux Persist with TypeScript


📈 14.9 Punkte

✅ Using the TypeScript generic type to create reusable components


📈 14.9 Punkte

✅ Understanding Props, Parent, and Child Components in React Native using TypeScript.


📈 14.9 Punkte

✅ Deploy serverless Lambda TypeScript API with function url using AWS CDK


📈 14.9 Punkte

✅ React Context-API Pro | Build state management using useContext + useReducer | Typescript


📈 14.9 Punkte

✅ Integrate MongoDB database with multiple collections using Mongoose in NestJS and Typescript


📈 14.9 Punkte

✅ I have built an API using TypeScript, Python, and Go, so you don't have to.


📈 14.9 Punkte

✅ Using keyof and typeof for types efficiently in TypeScript


📈 14.9 Punkte

✅ Using Cypress Component Testing in your Next.js Application with TypeScript and GraphQL


📈 14.9 Punkte

✅ Manage telescopic constructors with builder pattern using Typescript


📈 14.9 Punkte

✅ Stop Using TypeScript Interfaces


📈 14.9 Punkte

✅ How To Get Type-Safety Frontend Queries Like GraphQL Without GraphQL Using Typescript


📈 14.9 Punkte

✅ Why using AXIOS with Typescript?


📈 14.9 Punkte

✅ Stop using swagger-ui only, go with TypeScript SDK


📈 14.9 Punkte

✅ How to set up a Node Project using TypeScript in 2024


📈 14.9 Punkte











matomo

Datei nicht gefunden!