Using fetch

In the FAQ.vue Single File Component, we will use the standard fetch API of the web browser to retrieve the questions from our server. The request will be a very simple GET request to http://localhost:3000/questions with no authentication. Each question object will have title and content fields:

  1. Open FAQ.vue and start by adding the questions data property in the component script, which will hold the array of questions retrieved from the server. We also need an error property to display a message when something goes wrong during the network request:
      <script>
export default {
data () {
return {
questions: [],
error: null,
}
},
}
</script>
  1. Now we can add the questions and answers to the template with a v-for loop, and the following error message:
      <template>
<main class="faq">
<h1>Frequently Asked Questions</h1>

<div class="error" v-if="error">
Can't load the questions
</div>

<section class="list">
<article v-for="question of questions">
<h2 v-html="question.title"></h2>
<p v-html="question.content"></p>
            </article>
</section>
</main>
</template>

We are ready to fetch! The fetch API is promised-based and quite simple to use. Here is an example of fetch usage:

fetch(url).then(response => {
if (response.ok) {
// Returns a new promise
return response.json()
} else {
return Promise.reject('error')
}
}).then(result => {
// Success
console.log('JSON:', result)
}).catch(e => {
// Failure
console.error(e)
})

We first call fetch with the first parameter being the URL of the request. It returns a promise with a response object, which holds information about the request result. If it was successful, we use response.json(), which returns a new promise with the JSON parsed result object.

The request will be made inside the component as soon as it is created when the route is matched, which means that you should use the created life cycle hook in the component definition:

data () {
// ...
},
created () {
// fetch here
},

If everything goes well, we will set the questions property with the JSON parsed result. Or else we will display an error message.

  1. Start by calling fetch with the right URL:
      created () {
fetch('http://localhost:3000/questions')
},
  1. Add the first then callback with the response object:
      fetch('http://localhost:3000/questions').then(response => {
if (response.ok) {
return response.json()
} else {
return Promise.reject('error')
}
})
  1. We need another then callback since response.json() returns a new promise:
        // ...
}).then(result => {
// Result is the JSON parsed object from the server
this.questions = result
})
  1. Finally, we catch all possible errors to display the error message:
        // ...
}).catch(e => {
this.error = e
})

Here is a summary of our created hook:

created () {
fetch('http://localhost:3000/questions').then(response => {
if (response.ok) {
return response.json()
} else {
return Promise.reject('error')
}
}).then(result => {
this.questions = result
}).catch(e => {
this.error = e
})
},

We can rewrite this code using the async and await JavaScript keywords to make it look like sequential code:

async created () {
try {
const response = await fetch('http://localhost:3000/questions')
if (response.ok) {
this.questions = await response.json()
} else {
throw new Error('error')
}
} catch (e) {
this.error = e
}
},

You can now try the page, which should display a list of questions and answers:

To see if our error management is working, you can go to the console where the server is running, and stop it (for example, with the Ctrl+C keyboard shortcut). Then, you can reload the app and the following error message should be displayed:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.23.130