Skip to content
On this page

whenever

Category
Last Changed
21 days ago

Shorthand for watching value to be truthy.

Usage

import { useAsyncState, whenever } from '@vueuse/core'

const { state, isReady } = useAsyncState(
  fetch('https://jsonplaceholder.typicode.com/todos/1').then(t => t.json()),
  {},
)

whenever(isReady, () => console.log(state))
import { useAsyncState, whenever } from '@vueuse/core'

const { state, isReady } = useAsyncState(
  fetch('https://jsonplaceholder.typicode.com/todos/1').then(t => t.json()),
  {},
)

whenever(isReady, () => console.log(state))
// this
whenever(ready, () => console.log(state))

// is equivalent to:
watch(ready, (isReady) => {
  if (isReady) {
    console.log(state)
  }
})
// this
whenever(ready, () => console.log(state))

// is equivalent to:
watch(ready, (isReady) => {
  if (isReady) {
    console.log(state)
  }
})

Callback Function

Same as watch, the callback will be called with cb(value, oldValue, onInvalidate).

whenever(height, (current, lastHeight) => {
  if (current > lastHeight) {
    console.log(`Increasing height by ${current - lastHeight}`)
  }
})
whenever(height, (current, lastHeight) => {
  if (current > lastHeight) {
    console.log(`Increasing height by ${current - lastHeight}`)
  }
})

Computed

Same as watch, you can pass a getter function to calculate on each change.

// this
whenever(
  () => counter.value === 7, 
  () => console.log('counter is 7 now!'),
)
// this
whenever(
  () => counter.value === 7, 
  () => console.log('counter is 7 now!'),
)

Options

Options and defaults are same with watch.

// this
whenever(
  () => counter.value === 7, 
  () => console.log('counter is 7 now!'),
  { flush: 'sync' }
)
// this
whenever(
  () => counter.value === 7, 
  () => console.log('counter is 7 now!'),
  { flush: 'sync' }
)

Type Declarations

/**
 * Shorthand for watching value to be truthy
 *
 * @see https://vueuse.js.org/whenever
 */
export declare function whenever<T>(
  source: WatchSource<T | false | null | undefined>,
  cb: WatchCallback<T>,
  options?: WatchOptions
): WatchStopHandle
/**
 * Shorthand for watching value to be truthy
 *
 * @see https://vueuse.js.org/whenever
 */
export declare function whenever<T>(
  source: WatchSource<T | false | null | undefined>,
  cb: WatchCallback<T>,
  options?: WatchOptions
): WatchStopHandle

Source

SourceDocs

Contributors

Anthony Fu
freakzlike
donotloveshampo
Chung, Lian
Alex Kozack

Changelog

v7.6.2 on 2/13/2022
322cd - feat: add type for callback param (#1246)
v5.3.0 on 8/9/2021
8bc02 - feat: callback arguments (#661)
v4.7.0 on 4/4/2021
d6775 - feat: new function (#418)
whenever has loaded