How to have reactive getters on each element?

Let's say I have a createStore, and I want each element to have a getter, how should I go about this? I asked chat gpt, and he proposed this.
const [state, setState] = createStore([
{ name: 'John', age: 30 },
{ name: 'Mary', age: 25 },
{ name: 'Bob', age: 40 },
]);

const filteredState = createComputed(() =>
state.map((item) => ({
...item,
get filteredName() {
return item.name.toLowerCase().startsWith(nameFilter().toLowerCase());
},
}))
);
const [state, setState] = createStore([
{ name: 'John', age: 30 },
{ name: 'Mary', age: 25 },
{ name: 'Bob', age: 40 },
]);

const filteredState = createComputed(() =>
state.map((item) => ({
...item,
get filteredName() {
return item.name.toLowerCase().startsWith(nameFilter().toLowerCase());
},
}))
);
I think this looks ok enough, do you guys agree? Is there an alternative that lets you include getters right into the data I pass to createStore?
3 Replies
REEEEE
REEEEE15mo ago
You probably don't need to use computed. You could also do it in the data itself
const [state, setState] = createStore([
{ name: 'John',
age: 30,
get filteredName(){
return this.name.toLowerCase().startsWith(nameFilter().toLowerCase())
}
},
{ name: 'Mary', age: 25 },
{ name: 'Bob', age: 40 },
]);
const [state, setState] = createStore([
{ name: 'John',
age: 30,
get filteredName(){
return this.name.toLowerCase().startsWith(nameFilter().toLowerCase())
}
},
{ name: 'Mary', age: 25 },
{ name: 'Bob', age: 40 },
]);
chirptune
chirptune15mo ago
so, the createStore updates the this when it finds functions? oh my bad, hehe, it's in the docs sorry
REEEEE
REEEEE15mo ago
this refers to the object