Skip to content

Commit

Permalink
fix asyncStore impl
Browse files Browse the repository at this point in the history
  • Loading branch information
riccardoperra committed Nov 11, 2024
1 parent 03143af commit 5968f7b
Showing 1 changed file with 15 additions and 22 deletions.
37 changes: 15 additions & 22 deletions packages/app/src/lib/statebuilder/async.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
onCleanup,
Owner,
Setter,
untrack,
} from 'solid-js';
import {create} from 'statebuilder';

Expand Down Expand Up @@ -40,39 +41,31 @@ function makeAsyncSignal<T>(
},
): AsyncSignalState<T | undefined> {
const asyncState = createAsync(fetcher, options);
const [mode, setMode] = createSignal<'auto' | 'manual'>('auto');
const [signal, setSignal] = createSignal<T | undefined>(
options?.initialValue,
);

let disposer: () => void;
let innerOwner: Owner | null = null;

// TODO: In theory statebuilder support this, but it may not be a good choice. State should have access
// to sb resolved `context` (which is currently not resolved here)?
onCleanup(() => disposer());
createEffect(() => {
setSignal(() => asyncState());
});

const value = () => {
innerOwner = getOwner();
if (innerOwner && !disposer) {
// TODO: fix this 🤮. Some statebuilder states should register callbacks into consumer?
// Maybe the approach here should change
createRoot(dispose => {
disposer = dispose;
createComputed(
on(asyncState, latest => {
// Sync latest signal retrieved by asyncState in order to be available globally after navigation
setSignal(() => latest);
}),
);
});
const $mode = mode();
if ($mode === 'auto') {
return asyncState();
}
const $value = signal();
return $value;
return signal();
};

const set: Setter<T | undefined> = ((arg0: any) => {
setMode('manual');
setSignal(arg0);
}) as Setter<T | undefined>;

const state: AsyncSignalState<T | undefined> = Object.assign(value, {
raw: asyncState,
set: setSignal,
set,
});

return state;
Expand Down

0 comments on commit 5968f7b

Please sign in to comment.