Just to clarify, I want to mention that I am relatively new to working with Vue. Currently, I am in the process of developing a data visualization project to familiarize myself with the various concepts involved.
In order to fetch data from an API, I have implemented the following function as a composable:
import {ref} from 'vue'
const getData = (endpoint) => {
const data = ref([])
const error = ref(null)
const load = async() => {
try{
let response = await fetch("BASE_URL"+endpoint)
if (!response.ok){
throw Error('Error when trying to fetch data')
}
data.value = await response.json()
}
catch (err){
error.value = err.message
}
}
return{data, error, load}
}
export default getData
Currently, I am fetching the data within the setup function and displaying it on the template. However, I require assistance in making another API call after a specific event, such as an @click event, in order to update the data displayed on the page.
The code snippet below illustrates my current approach, where the handleClick function is not functioning as intended. The desired outcome is for the template to display data from endpoint2 upon clicking the button. It is possible that I have misunderstood some key concepts, which is why I am reaching out to the community for guidance. Your help would be greatly appreciated.
<template>
<div>
<button @click="handleClick">click me</button>
</div>
<div>{{data}}</div>
</template>
<script>
import {ref} from 'vue'
import getData from '../composables/getData'
export default {
name: 'HomeView',
setup(){
const {data, error, load} = getData('endpoint1')
load()
const handleClick = () => {
console.log('clicked')
const {data, error, load} = getData('endpoint2')
load()
}
return {data, handleClick}
},
}
</script>