Skip to content
Tutorials Center
My learning

Topics

Lesson 80 of 87 ยท Projects

Project: Movie Search with Router and API

Build a movie search app in Vue 3: debounced search with request cancellation, loading, empty and error states, a reusable useAsyncData composable, a hash router with a detail page and URL-synced query.

Searching an API and opening a detail page is the heart of countless real apps: a store catalogue, a job board, a documentation site. This project builds a movie finder and, along the way, solves three problems that bite every beginner: typing fires too many requests, old responses arrive after new ones, and a failing request leaves the screen stuck.

The API is a mock (the preview cannot reach a real server), but you will call it exactly as you would call a real one, so replacing it later changes one function. You will build the project in two stages: first the search box with all its states, then a router with a shareable URL, a detail page and a composable that both pages reuse. Background: fetching data, watch, composable patterns and routing concepts.

Design first

A request is always in exactly one situation, so model it as one status value: idle, loading, ok, empty or error. One status, one block of template; there is no combination of flags to get wrong.

stateDiagram-v2
    [*] --> idle
    idle --> loading: query has 2+ letters
    loading --> ok: results
    loading --> empty: no results
    loading --> error: request failed
    ok --> loading: query changes
    empty --> loading: query changes
    error --> loading: query changes
    ok --> idle: query cleared

Every change of the query starts a new request. The old one is cancelled.

Two rules keep the experience good:

  • Debounce: wait for a short pause in typing (300 ms) before sending. Typing "matrix" must not send six requests.
  • Cancel stale requests: when the query changes, abort the previous request so its late answer cannot overwrite the new one.

Both rules have the same shape, "undo the earlier work when the input changes", and watch offers a perfect tool: the onCleanup callback runs before the watcher's next run. Clear the timer (debounce) and abort the request (cancel) in one place.

Stage 1: debounced search with every state

The mock API searchMovies(query, { signal }) waits a bit, filters a small list and respects AbortSignal. If you search for the word error, it fails on purpose, so you can see the error state.

Stage 1: debounce, cancel and the five states

Type matrix quickly: the counter shows one request, not six, because each keystroke's cleanup cancelled the pending timer. Then type ma, wait, and add r while the first search is still "Searching..." (within half a second): the first request is aborted, and only the second one's answer can reach the screen. Search error and zzz for the other two states.

What to notice:

  1. Aborts are not errors. The catch ignores AbortError. If it showed it, every fast typist would see error messages.
  2. No flag soup. There is no isLoading, hasError and isEmpty to keep in agreement. The template uses a v-if chain on one status.
  3. Trim before measuring. Spaces alone should not trigger a search.
  4. Short queries are a state, not a request. Returning early with idle saves the server from useless work like searching for a single letter.

Stage 2: a router, a detail page and a reusable composable

Now the app grows. A result should open a detail page, the address should reflect the search so people can bookmark and share it, and the back button should return to the results. That needs a router and a cleaner structure.

First, extract the loading pattern. The search and the detail page both need "run an async function whenever its input changes, cancel the previous one, expose a status". That is a composable, useAsyncData(source, loader), which returns { data, error, status }. Because it has one job and no knowledge of movies, both views reuse it.

Second, a hash router, written with plain reactivity like in Build a Tiny Hash Router (the lesson runner has no Vue Router package; the real one is in Vue Router basics). The current hash is a ref; a computed route turns it into { name, id, q }. The search box does not call the API itself any more: after a debounce it writes the query into the URL (#/?q=matrix), and the search view loads whatever the URL says. The URL is the single source of truth.

Stage 2: URL-driven search, detail route and useAsyncData

Search for ma, open a movie, then use Back to results: the search comes back with your query, because the query lives in the address. If you change the address to #/movie/99 (on a normal page you can type it), the detail view shows the not-found error instead of a blank page. The same structure also makes the browser back button return to your previous search.

How the pieces fit together:

  • useAsyncData owns the pattern. It takes a source (a getter) and a loader ((value, { signal }) => Promise). It cancels the previous run in onCleanup, ignores aborts, and maps results to a status. A getter that returns null means "nothing to load", which is how the search view says "the query is too short". This is the same idea as the useFetch in composable patterns, generalized to any loader.
  • StatusView is a small presentational component. It renders the status text for loading, error and empty, and the real content through a slot for ok. The two views do not repeat the same v-if chain.
  • The URL is the source of truth. The search view does not call the API when you type. It writes the (debounced) text into the hash, the router computes route, and useAsyncData reacts to the prop. Reload the page or send the link to a friend and the same results appear.
  • One history entry per settled search. Because the debounce waits for a pause, assigning location.hash adds one history entry per search, not one per keystroke, and Back steps through your searches. (Vue Router offers router.replace when you would rather overwrite the current entry; a bare history.replaceState is not available inside the sandboxed preview.)
  • :key on the views forces a fresh component when the movie changes, so no stale state leaks from one detail page to the next.
  • Links keep a real href but navigate through go(). A real href keeps middle-click, copy-link and screen readers working. The click handler calls go() (which sets location.hash) because the preview document does not live at a normal address, so a bare #/... link would not behave. On an ordinary page a plain <a href="#/movie/1"> works, and Vue Router's <router-link> does all of this for you.
  • Unknown routes get a not-found view. Always have one.

With the real Vue Router the same structure appears as routes (/ with a query, /movie/:id), useRoute() for params and query, and router.replace({ query: { q } }) for the debounced update. The composable and the views would not change (Vue Router basics).

Where to go next

  • Add a "recent searches" list kept in a store and shown while the box is empty.
  • Show the previous results dimmed while a new search loads instead of replacing them with "Loading...". Keep data until the new response arrives.
  • Add pagination (?page=2) as another part of the URL, and a genre filter as a second parameter.
  • Switch the mock to a real API: replace the two functions at the top. Remember to check response.ok and to URL-encode the query (fetching data).
  • Test useAsyncData on its own with a fake loader (testing composables).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the onCleanup callback do in the Stage 1 watcher?

    Vue calls the previous cleanup before the callback runs again, which is the perfect place to undo the earlier timer and request.
  2. 2. Why does the catch block ignore AbortError?

    Abort happens whenever the user keeps typing. Showing it as an error would flash error messages during normal use.
  3. 3. In Stage 2, where does the search text really live after the debounce?

    The URL is the source of truth. That makes searches bookmarkable and shareable and keeps the back button meaningful.
  4. 4. Why use one status value (idle, loading, ok, empty, error) instead of separate booleans?

    With one status, the template shows exactly one block. With several flags you must keep them in agreement by hand.
  5. 5. What is the benefit of useAsyncData accepting a loader function?

    Separating the 'when and how to run' from the 'what to fetch' lets several views share the same tested logic.

Summary

  • Model a request as one status; render one template block per status and keep empty and error states friendly.
  • Debounce and cancel with a single watch and onCleanup: clear the timer, abort the request.
  • Treat abort as a normal outcome, not an error.
  • Extract repeated request logic into a composable such as useAsyncData(source, loader) and a small StatusView component.
  • Put the query in the URL so searches can be shared, and update it only after the debounce so history stays tidy.
  • Always provide a not-found route and an error state for missing data.

Next: a live connection, Project: Chat App.