Replies: 2 comments 5 replies
-
The reactive graph can start and stop wherever so it has no place to pull from when it restarts. The stack is gone. For a context there are are only 2 hierarchical places you can reliably tap, the reactive graph or the DOM tree. DOM tree doesn't suit us as components aren't tied to specific DOM element. The 3rd option would be trapping it in a closure like a HOC that passed context as 2nd argument to a component. But that gets bulky without access to the frameworks internals. If you don't care about hierarchical resolution I suggest looking at the bottom of the Context docs on the next branch. Otherwise technically you make your own context mechanism using the reactive graph by writing to the context prop of the reactive owner. |
Beta Was this translation helpful? Give feedback.
-
finally, I made a context general enough both for sync functions and solid components: import { createComputed, getOwner, untrack } from "solid-js";
type SolidFunctionContext<Value> = {
provide<Result>(value: Value, func: (value: Value) => Result): Result;
use(): Value;
};
type SolidFunctionContextWithoutDefaultValue<Value> = {
provide<Result>(value: Value, func: (value: Value) => Result): Result;
use(): Value | undefined;
};
export function createSolidFunctionContext<Value>(
defaultValue: Value
): SolidFunctionContext<Value>;
export function createSolidFunctionContext<
Value
>(): SolidFunctionContextWithoutDefaultValue<Value>;
export function createSolidFunctionContext<Value>(
defaultValue?: Value
):
| SolidFunctionContext<Value>
| SolidFunctionContextWithoutDefaultValue<Value> {
const id = Symbol("context");
return {
provide: (value, func) => {
let result: ReturnType<typeof func>;
let err: Error;
createComputed(() => {
// @ts-ignore
getOwner()![id] = value;
untrack(() => {
try {
result = func(value);
} catch (e) {
err = e;
}
});
});
if (err!) throw err;
return result!;
},
use: () => {
const contextValue = lookup(getOwner(), id);
return contextValue !== undefined ? contextValue : defaultValue;
},
};
}
function lookup(owner: ReturnType<typeof getOwner>, key: symbol | string): any {
if (owner) {
// @ts-ignore
const result = owner[key];
return result !== undefined ? result : lookup(owner.owner, key);
} else {
return undefined;
}
} |
Beta Was this translation helpful? Give feedback.
-
Context pattern is great but it is only for components now. I've managed to create a generic function context, it works well, but as it was not connected to the reactive owner, it does not work for dynamic component.
I hope solid could provide a generic context pattern with itself to support general function call. Here is my solution for reference:
Tests:
Beta Was this translation helpful? Give feedback.
All reactions