Get data from API with Axios, API calls with Axios

February 17th, 2023

API Calls with Axios

1npm install axios
1const emails = ref([])
2 
3async function getEmails(){
4 await axios
5 .get('http://localhost:3000/emails')
6 .then((response) => {
7 // console.log(response)
8 emails.value = response.data
9 })
10 .catch((error) => console.log(error))
11}

async...await

1const emails = ref([])
2const error = ref(null)
3 
4async function getEmails(){
5 try {
6 let response = await axios.get('http://localhost:3000/emails')
7 emails.value = response.data
8 
9 } catch(err) {
10 error.value = err
11 }
12}

try.. catch...finally, async...await

1const emails = ref(null)
2const loading = ref(false)
3const error = ref(null)
4 
5async function getEmails(){
6 loading.value = true
7 try {
8 let response = await axios.get('http://localhost:3000/emails')
9 emails.value = response.data
10 } catch(ex) {
11 error.value = ex
12 } finally {
13 loading.value = false
14 }
15 
16}

Related Posts