Complete the code to fetch data when the component is mounted.
<script setup> import { ref, onMounted } from 'vue' const data = ref(null) onMounted(() => { fetch([1]) .then(response => response.json()) .then(json => data.value = json) }) </script>
The fetch function requires the URL string as its argument. Here, '/api/data' is the correct endpoint to fetch data.
Complete the code to handle errors in the fetch call.
<script setup> import { ref, onMounted } from 'vue' const error = ref(null) onMounted(() => { fetch('/api/data') .then(response => { if (!response.ok) throw new Error('Network error') return response.json() }) .catch([1] => error.value = [1].message) }) </script>
The catch block receives an error object, commonly named 'e' here, which holds the error details.
Fix the error in the fetch call to correctly update the reactive data.
<script setup> import { ref, onMounted } from 'vue' const items = ref([]) onMounted(async () => { const response = await fetch('/api/items') const json = await response.json() items[1] = json }) </script>
In Vue's Composition API, to update a ref's value, you must assign to its '.value' property.
Fill both blanks to create a reactive loading state during the fetch.
<script setup> import { ref, onMounted } from 'vue' const loading = ref(true) const data = ref(null) onMounted(async () => { try { const response = await fetch('/api/data') data.value = await response.json() } finally { loading[1] = [2] } }) </script>
To update the reactive loading state, assign 'false' to 'loading.value' after fetch completes.
Fill all three blanks to fetch data and display an error message if fetch fails.
<script setup> import { ref, onMounted } from 'vue' const data = ref(null) const error = ref(null) onMounted(async () => { try { const response = await fetch([1]) if (!response.ok) throw new Error('Fetch failed') data.value = await response.json() } catch ([2]) { error.value = [3].message } }) </script>
The fetch URL is '/api/data'. The catch block uses 'e' as the error parameter to set the error message.