S
SolidJS10mo ago
bigblind

Best practices for reactively updating a store

I know you can use derived signals in SolidJS, but, is there a way to somehow make a store "derive" from a signal? The only way I can see to do this would be in an effect, but the effect docs say that it's not meant for functions that write reactive state. More specifically, I have a resource, and once that loads, I'd like to put it in the store. If that's a bad idea, is there some other way to have Suspense track an asynchronous operation that updates a store?
4 Replies
lobster theremin
lobster theremin10mo ago
function createDeepSignal<T>(value: T): Signal<T> {
const [store, setStore] = createStore({
value,
});
return [
() => store.value,
(v: T) => {
const unwrapped = unwrap(store.value);
typeof v === "function" && (v = v(unwrapped));
setStore("value", reconcile(v));
return store.value;
},
] as Signal<T>;
}
const [resource] = createResource(fetcher, {
storage: createDeepSignal,
});
function createDeepSignal<T>(value: T): Signal<T> {
const [store, setStore] = createStore({
value,
});
return [
() => store.value,
(v: T) => {
const unwrapped = unwrap(store.value);
typeof v === "function" && (v = v(unwrapped));
setStore("value", reconcile(v));
return store.value;
},
] as Signal<T>;
}
const [resource] = createResource(fetcher, {
storage: createDeepSignal,
});
https://docs.solidjs.com/references/api-reference/basic-reactivity/createResource#v150 you can use storage to return a store from a resource fetch
bigblind
bigblindOP10mo ago
Hmm I see, that might work I know I'm nitpicking here, but the only thing I dislike about that is now I'm coupling the place where I'm creating the store with the place where I fetch the resource. I'm also pondering if there's a way to rewrite createDeepSignal to retain the ability to set values at a specific path in the store, rather than setting the entire value.
bigmistqke
bigmistqke10mo ago
use a getter?
bigmistqke
bigmistqke10mo ago
Solid Playground
Quickly discover what the solid compiler will generate from your JSX template
Want results from more Discord servers?
Add your server