JAVASCRIPT

Implement Reactive Auto-Saving with Vue 3's `watchEffect`

Utilize Vue 3's `watchEffect` to automatically trigger side effects, like saving form data to local storage, whenever reactive dependencies change.

// src/App.vue
<script setup>
import { ref, watchEffect, onMounted } from 'vue'

const message = ref('')
const savedMessage = ref('')

// Simulate an API call or local storage save
const saveMessage = (data) => {
  console.log('Saving message:', data)
  localStorage.setItem('autoSaveMessage', data)
  savedMessage.value = data
}

// Auto-save whenever 'message' changes
watchEffect(() => {
  if (message.value.length > 0) {
    saveMessage(message.value)
  }
}, {
  // Optional: Add a debounce for performance if saving frequently
  // A full debounce implementation would involve setTimeout/clearTimeout
  // For this simple example, we omit it to focus on watchEffect.
})

onMounted(() => {
  const stored = localStorage.getItem('autoSaveMessage')
  if (stored) {
    message.value = stored
  }
})
</script>

<template>
  <div>
    <h1>Auto-Save Demo</h1>
    <input type="text" v-model="message" placeholder="Type something...">
    <p>Current Message: {{ message }}</p>
    <p>Last Saved: {{ savedMessage }}</p>
  </div>
</template>
How it works: This snippet demonstrates `watchEffect` for creating reactive side effects. It automatically calls the `saveMessage` function whenever the `message` ref changes, effectively implementing an auto-save feature. Unlike `watch`, `watchEffect` automatically tracks its reactive dependencies, making it concise for scenarios where the effect itself determines what to react to. It also loads the saved message on mount.

Need help integrating this into your project?

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

Hire DigitalCodeLabs