JAVASCRIPT

Performing Side Effects with watch in Vue 3

Implement a `watch` function in Vue 3's Composition API to execute side effects or logic whenever a specific reactive data source changes. Ideal for async ops.

import { ref, watch, onMounted } from 'vue';

export default {
  setup() {
    const userId = ref(1);
    const userData = ref(null);
    const isLoading = ref(false);
    const error = ref(null);

    const fetchUser = async (id) => {
      isLoading.value = true;
      error.value = null;
      userData.value = null;
      try {
        const response = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`);
        if (!response.ok) {
          throw new Error('Failed to fetch user data');
        }
        userData.value = await response.json();
      } catch (err) {
        error.value = err.message;
      } finally {
        isLoading.value = false;
      }
    };

    // Watch for changes in userId and refetch data
    watch(userId, (newId, oldId) => {
      console.log(`User ID changed from ${oldId} to ${newId}`);
      fetchUser(newId);
    }, { immediate: true }); // immediate: true runs the watcher immediately on component setup

    const nextUser = () => {
      userId.value++;
    };

    return {
      userId,
      userData,
      isLoading,
      error,
      nextUser
    };
  }
};
How it works: This snippet uses Vue 3's `watch` function to perform side effects. It watches the `userId` ref, and whenever `userId.value` changes, the provided callback function is executed. In this example, the callback triggers an asynchronous `fetchUser` function to load new data. The `immediate: true` option ensures the `fetchUser` function runs once initially when the component is mounted. This pattern is essential for reacting to changes in reactive data, such as fetching data from an API based on user input or route parameters.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs