Handling Side Effects with watchEffect in Vue.js

Using watchEffect for Side Effects

Side effects are operations that interact with the outside world or have effects beyond the function’s scope. With watchEffect, you can manage these side effects in a clean and reactive manner.

Dynamic Data Fetching

import { ref, watchEffect } from 'vue';

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

    watchEffect(async () => {
      const response = await fetch(`https://jsonplaceholder.typicode.com/users/${userId.value}`);
      userData.value = await response.json();
    });

    function updateUserId(newId) {
      userId.value = newId;
    }

    return {
      userId,
      userData,
      updateUserId
    };
  }
}

In this example, watchEffect tracks userId and fetches user data whenever userId changes. The side effect of fetching data is managed reactively and cleanly.

Thank You.

Leave a comment

Your email address will not be published. Required fields are marked *