Skip to content

Commit

Permalink
fix: log error if computed throws on first run
Browse files Browse the repository at this point in the history
  • Loading branch information
mihar-22 committed Nov 25, 2022
1 parent d324b95 commit 8582879
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 8 deletions.
1 change: 1 addition & 0 deletions .scripts/bundle.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ async function main() {
watch: hasArg('-w'),
define: {
__DEV__: dev ? 'true' : 'false',
__TEST__: 'false',
},
external: ['@maverick-js/scheduler'],
};
Expand Down
1 change: 1 addition & 0 deletions src/globals.d.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
declare global {
const __DEV__: boolean;
const __TEST__: boolean;
}

export {};
22 changes: 14 additions & 8 deletions src/observables.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,8 +159,7 @@ export function isObservable<T>(fn: MaybeObservable<T>): fn is Observable<T> {
*/
export function computed<T>(fn: () => T, options?: ComputedOptions<T>): Observable<T> {
let currentValue,
init = false,
effect = (options as any)?._e;
init = false;

const isDirty = options?.dirty ?? notEqual;

Expand Down Expand Up @@ -193,12 +192,20 @@ export function computed<T>(fn: () => T, options?: ComputedOptions<T>): Observab
dirtyNode($computed);
}
} catch (error) {
if (!init && !effect) throw error;
if (__DEV__ && !__TEST__ && !init && !(options as any)?.effect) {
console.error(
`computed \`${$computed.id}\` threw error during first run, in prod this` +
` will be fatal. Prefer an \`effect\` if the return value is not being used.`,
'\n',
error,
);
}

handleError($computed, error);
return currentValue;
}

init = true;
if (__DEV__) init = true;
$computed[DIRTY] = false;
if (!$computed[OBSERVING]?.size) dispose($computed);
}
Expand Down Expand Up @@ -236,10 +243,9 @@ export function effect(fn: Effect, options?: { id?: string }): StopEffect {
const result = fn();
result && onDispose(result);
},
{
id: __DEV__ ? options?.id ?? 'effect' : undefined,
_e: true,
} as ComputedOptions<unknown>,
__DEV__
? ({ id: options?.id ?? 'effect', effect: true } as ComputedOptions<unknown>)
: undefined,
);
$effect();
return () => dispose($effect);
Expand Down
1 change: 1 addition & 0 deletions vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { defineConfig } from 'vite';
export default defineConfig({
define: {
__DEV__: 'true',
__TEST__: 'true',
},
// https://vitest.dev/config
test: {
Expand Down

0 comments on commit 8582879

Please sign in to comment.