DEV Community

Florian Klenk
Florian Klenk

Posted on

Svelte reactive $state recursive classes

In my new learning project I have a recursive data structure that looks as follows:

type CategoryType = {
    name: string;
    percent: number;
    percentages: {
        name: string;
        percent: number;
    }[];
    amount?: number | undefined;
} & {
    categories: CategoryType[];
}
Enter fullscreen mode Exit fullscreen mode

Categories might have an array of more Categories which might have other categories again and so on.

Now I want to achieve that when I add a new category to the $state that a new category component gets rendered.

Image description

This commit does not work as expected. Svelte detects when I add something to the root categories. If I add a category to a root category the view won't update as you can see:

This is mainly due to the fact that I'm using classes in my state and these classes don't have reactive properties.
After reading this article which I can highly recommend I know now that I can also use the $state rune within my class.

All I need to do is to rename the existing file where I defined my category class to category.svelte.ts so that svelte detects I'm using some svelte magic in that file.
Then I can start defining my properties as follows

export class Category {
  name = $state<string>();
  percent = $state<number>(0);
  categories = $state<Category[]>([]);
  percentages = $state<PercentageSchemaType[]>([]);
  parent = $state<Category | undefined>();
...
Enter fullscreen mode Exit fullscreen mode

ACI image

ACI.dev: Best Open-Source Composio Alternative (AI Agent Tooling)

100% open-source tool-use platform (backend, dev portal, integration library, SDK/MCP) that connects your AI agents to 600+ tools with multi-tenant auth, granular permissions, and access through direct function calling or a unified MCP server.

Star our GitHub!

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.

Postmark Image

"Please fix this..."

Focus on creating stellar experiences without email headaches. Postmark's reliable API and detailed analytics make your transactional emails as polished as your product.

Start free