Watching for Changes

A computed value works out a value to show. Sometimes, though, when data changes, you want to do something: save it, print it, send it somewhere. Things like that are called side effects, and for them, Vue has watchers, which you make with watch():

import { ref, watch } from "vue";

const category = ref("all");

watch(category, (newValue, oldValue) => {
    console.log(`Now showing: ${newValue} (before: ${oldValue})`);
});

watch() gets two arguments. The first is what to watch: a ref or a computed value, without .value. The second is a function that Vue runs after every change, with the new value and the old one. When the customer chooses tea, the console shows:

Now showing: tea (before: all)

The function doesn't return anything; it does its job, and that's it. And it doesn't run when the app starts, only after a change. Often, you need only the new value, and then you leave out the old one: (value) => { … }.

A typical side effect is saving in localStorage. In this exercise, the customer types a name for the order, and the app should remember it for next time. A watcher saves the name after each change, and when the app starts, it reads it back. You know from the JavaScript course that getItem() returns null when nothing is saved, so check that:

const saved = localStorage.getItem("color");
const color = ref(saved === null ? "green" : saved);

In the preview, each click on Run starts the app again, and while you have the exercise open, the app finds what it saved before. The Clear saved data button in the console deletes it, as if the app had never been opened.

A typical mistake is watch(name.value, …). That gives watch() the text in the ref, not the ref, and a text alone can't change, so Vue has nothing to watch. The console then shows a warning that starts with [Vue warn]: Invalid watch source.

Instructions

  1. Watch name, and every time it changes, save it in localStorage under the key name.

  2. When the app starts, read the saved name, so that the field and the greeting show it. Without a saved name, the field starts empty. Try it: type your name and click Run.