Question 27
Consider the following HTML, which includes Vue 2 and Vuex CDN links.
<div id="app"> <p v-if="userData">User: {{ userData.name }}</p> <p v-else>No user data available</p> </div>
<script> const store = new Vuex.Store({ state: { userData: null }, mutations: { setUserData(state, data) { state.userData = data; } }, actions: { fetchUserData({ commit }) { return fetch('https://httpstat.us/500') .then(response => { if (!response.ok) throw new Error('Network error'); return response.json(); }) .then(data => { commit('setUserData', data); }, error => { commit('setUserData', { name: 'Luke' }) }) .catch(() => { commit('setUserData', null); }); } } });
new Vue({ el: '#app', store, created() { this.$store.dispatch('fetchUserData'); },
computed: { userData() { return this.$store.state.userData; } } });
</script>What will be rendered on the browser, if the fetch request gets back 500 status code?
The userData in the store is set to the data from the API.
User: null
The error will be logged, Nothing will be displayed
User: Luke