@@ -29,17 +29,30 @@ export const renderAsyncComputed = <T, R = unknown>(
2929
3030export class AsyncComputedState < T , R = unknown > {
3131 private _invalidate = signal ( 0 ) ;
32- private _initial ?: T ;
33- private _state ?: AsyncComputed < T > ;
32+ private _computed ?: AsyncComputed < T > ;
33+ private _state = signal < T | undefined > ( undefined ) ;
3434 get state ( ) {
35- this . _state ??= new AsyncComputed (
36- ( abortSignal : AbortSignal ) => {
37- this . _invalidate . get ( ) ;
38- return this . _fetch ( abortSignal ) ;
39- } ,
40- this . _initial ? { initialValue : this . _initial } : undefined ,
41- ) ;
42- return this . _state ;
35+ this . computed . run ( ) ;
36+ return this . _state . get ( ) ;
37+ }
38+
39+ get computed ( ) {
40+ if ( this . _computed == null ) {
41+ const initial = this . _state . get ( ) ;
42+ this . _computed = new AsyncComputed (
43+ async ( abortSignal : AbortSignal ) => {
44+ this . _invalidate . get ( ) ;
45+
46+ const state = await this . _fetch ( abortSignal ) ;
47+ this . _state . set ( state ) ;
48+
49+ return state ;
50+ } ,
51+ initial ? { initialValue : initial } : undefined ,
52+ ) ;
53+ }
54+
55+ return this . _computed ;
4356 }
4457
4558 constructor (
@@ -50,7 +63,8 @@ export class AsyncComputedState<T, R = unknown> {
5063 } ,
5164 ) {
5265 if ( options != null ) {
53- this . _initial = options . initial ;
66+ this . _state . set ( options . initial ) ;
67+
5468 if ( options . autoRun === true ) {
5569 this . run ( ) ;
5670 }
@@ -60,7 +74,7 @@ export class AsyncComputedState<T, R = unknown> {
6074 if ( force ) {
6175 this . invalidate ( ) ;
6276 }
63- this . state . run ( ) ;
77+ this . computed . run ( ) ;
6478 }
6579
6680 invalidate ( ) {
@@ -73,6 +87,6 @@ export class AsyncComputedState<T, R = unknown> {
7387 complete ?: ( value : T | undefined ) => R ;
7488 error ?: ( error : unknown ) => R ;
7589 } ) {
76- return renderAsyncComputed ( this . state , config ) ;
90+ return renderAsyncComputed ( this . computed , config ) ;
7791 }
7892}
0 commit comments