S
SolidJS•12mo ago
itsyoboieltr

createStore default value with anonymous function

In react I would do something like:
const [array, setArray] = useState(() => {
/* some computation */
return [...data];
});
const [array, setArray] = useState(() => {
/* some computation */
return [...data];
});
Can I do something similar with solid?
3 Replies
REEEEE
REEEEE•12mo ago
I personally haven't seen that before in React 🤔 But you could just call the function immediately.
const [array, setArray] = createStore((() => {
/* some computation */
return [...data];
})());
const [array, setArray] = createStore((() => {
/* some computation */
return [...data];
})());
itsyoboieltr
itsyoboieltrOP•12mo ago
thats exactly what I ended up doing, but it looks soo ugly :DD btw, to justify the use case: I am getting the queried data from the solid-query cache, and want it to be available as the default state of the store. But this data is not always available of course, it is only available if the cache already has an entry. This is the current solution I ended up doing:
const [rows, setRows] = createStore(
(() => {
const data = queryClient.getQueryData<(typeof query)['data']>(
queryKey(),
);
return data ? doComputation(data) : [];
})(),
);
const [rows, setRows] = createStore(
(() => {
const data = queryClient.getQueryData<(typeof query)['data']>(
queryKey(),
);
return data ? doComputation(data) : [];
})(),
);
(it is not a derived state, because I need to be able to set it later, so I also need a setter. It is a store (vs a signal) because it is an array)
mdynnl
mdynnl•12mo ago
react provides that callback api because it has to provide it or else the initialization code will be running along with the component. but in solid, a component only initializes once so there's no point doing that.
Want results from more Discord servers?
Add your server