Build a component that fetches data and caches it using a computed property or watcher.
Code Playground
JavaScript (V8)
Loading...
Console Output
// Output will appear here...
// For React: ReactDOM.createRoot(rootElement).render(<App />);
// For React: ReactDOM.createRoot(rootElement).render(<App />);
Recommended Answer
<template>
<!-- ... -->
</template>
<script setup>
import { ref, computed } from 'vue';
const cache = new Map();
const userId = ref(1);
const userData = computed(async () => {
if (cache.has(userId.value)) {
return cache.get(userId.value);
}
const res = await fetch(`.../${userId.value}`);
const data = await res.json();
cache.set(userId.value, data);
return data;
});
</script>