Skip to content
intermediate

Review: a watcher that watched a string once

This is recall. The code looks finished and is wrong. Find the defect and fix it. You are graded on tests you cannot see.

You asked a model for a search composable: hold a query string, and each time it changes, call the provided `onSearch` with the new value — skipping blank queries. It produced this, with tests. The tests pass.

import { reactive, watch } from 'vue'

export interface SearchState {
  query: string
}

export function useSearch(onSearch: (query: string) => void) {
  const state = reactive<SearchState>({ query: '' })

  watch(state.query, (query) => {
    if (query.trim().length > 0) {
      onSearch(query)
    }
  })

  function setQuery(query: string): void {
    state.query = query
  }

  return { state, setQuery }
}
review — find the defectCtrl+↵ submits · Ctrl+Shift+↵ runsstarter code