November 2017
Beginner to intermediate
398 pages
8h 42m
English
Now, we are going to write the $fetch method. We will take most of the code we used in the created hook of the FAQ component:
export async function $fetch (url) { const response = await fetch(`${baseUrl}${url}`) if (response.ok) { const data = await response.json() return data } else { const error = new Error('error') throw error } }
We export it so we can use it in our plain JavaScript code too. The url parameter is now just the path of the query without the domain, which is now in our baseUrl variable--this allows us to change it easily without having to refactor each component. We also take care of the JSON parsing, since all the data from the server will be encoded in JSON.
Read now
Unlock full access