fn

refDefault

v0.0.14testeddemo

Wrap a writable ref so that reads fall back to a default value whenever the source holds null or undefined, while writes pass straight through to the source. The default may itself be reactive (a ref, getter, or plain value), so the fallback can track other state. Implemented as a single writable computed — no watchers, no extra refs, nothing to tear down — which keeps it allocation-light and SSR-safe (it never touches the DOM).

Examples

ts
const raw = ref<string | null>(null);
const name = refDefault(raw, 'anonymous');
name.value; // 'anonymous'
raw.value = 'ada';
name.value; // 'ada'
name.value = 'grace';
raw.value; // 'grace' — writes pass through
ts
// The default can be reactive
const fallback = ref('guest');
const user = refDefault(ref<string | null>(null), fallback);
fallback.value = 'visitor';
user.value; // 'visitor'

Demo

Loading demo…

Signature

ts
export function refDefault<T>(
  source: Ref<T | null | undefined>,
  defaultValue: MaybeRefOrGetter<T>,
): RefDefaultReturn<T>{ ... }

Type Parameters

T

Parameters

ParameterTypeDescription
sourceRef<T | null | undefined>The source ref to read through and write back to
defaultValueMaybeRefOrGetter<T>Fallback returned when the source is null/undefined (can be reactive)

Returns

RefDefaultReturn<T>A writable computed ref that never reads as null/undefined