getOwner and runWithOwner
The current owner is a global register that is set while a component body, an effect or a root callback runs synchronously.
The current owner is a global register that is set while a component body, an effect or a root callback runs synchronously. After an await or inside a timer or promise callback it is gone, so a hook called there has no owner. Capture the owner first, restore it with runWithOwner(owner, fn):
src/after-await.tsts
import { createRoot, flushSync, getOwner, runWithOwner, useEffect } from "@shadow-js/core";
async function load(): Promise<string> {
return "data";
}
const dispose = createRoot((stop) => {
const owner = getOwner();
const ready = load().then((data) => {
// Without runWithOwner there is no owner here and useEffect would warn NO_OWNER_EFFECT.
runWithOwner(owner, () => {
useEffect(() => {
console.log(`effect saw ${data}`);
});
});
});
return { stop, ready };
});
await dispose.ready;
flushSync();
dispose.stop();
effect saw datarunWithOwner(owner, fn) runs fn untracked with owner as the current owner and restores the previous one afterward. Passing an owner that has been disposed warns RUN_WITH_DISPOSED_OWNER and runs fn with no owner.