K. Anye
K. Anye

Reputation: 198

Svelte reactivity - Class member change doesn't reflect on UI

I'm currently creating a table manager web component which consists of a few different components, like data-table, search-bar etc. I manage it separately because there are cases when the table or search bar is not used, but when they're used together they use the same class as an input. The search bar calls one of the class's methods for search and it filters the data accordingly, and however the data property is changed in the class, it won't reflect on the UI only if I do some action to refresh is ( e.g. checking a checkbox ).

So I'm changing one member of a class by a class method call in component A and I want it to reflect in component B.

export let config: TableConfig = new TableConfig();
$: setConfig(config);

...

// Search function:
config.quickSearch(quickSearchValue);

I loop through the config.data to show some data. After the search, the data member changes and if I use a setInterval to log the config in the table component, it shows the changed data but the UI won't refresh.

Maybe my approach is completely wrong, but this is how I did it in Angular, but it had a lot of unnecessary dependencies, so now I'm trying to get rid of that.. So my main goal is to use this anywhere, like Svelte, Angular, VanillaJS etc.

EDIT:

REPL example: https://svelte.dev/repl/311538f2cf52484f8d0ac3aeae7540ea?version=3.31.0

Upvotes: 2

Views: 1957

Answers (1)

Stephane Vanraes
Stephane Vanraes

Reputation: 16451

The UI does not change, because as far as Svelte knows there has been no change in data. You would have to add a subscription system to your class if you want to keep that structure.

Svelte however has a better approach for sharing data across components and that is stores. What you could do in your situation is create a custom store enter link description here that encapsulates the logic you used to have in a class. That way you can simply subscribe to this store in one component and trigger an update in another one, benefiting from Svelte's reactivity.

Upvotes: 1

Related Questions