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

Top comments (0)