I have this code snippet:
export default defineComponent({ name: "filter", props: {}, setup() { const states = useCounterStore(); return { states }; }, data() { return { items: [], }; }, methods: {}, mounted() { fetch("http://localhost:3000/tags") .then((res) => res.json()) .then((data) => { this.items = data; alert(data); }) .catch((err) => console.log(err.message)); }, });
fetch is called twice and I don't know why. Is there any solution?
From the shared code, it appears that the component is being installed twice, so you may want to look at the component that is installing it.
However, you can store the response so it is not fetched multiple times
Because
tags
is declared outside the component, it behaves like a global variable and is therefore stateful. Each time the componentis set
, it will check if the tag is loaded and then use the cached data, or load it and update the item afterwards.Some notes on this example...
Ideally, such logic should be in a separate file and have better abstraction. For example, if you have multiple APIs, they can share this functionality, eg.
const {status, data, error} = useApiCall('/tags')
. And you can usetags
directly instead of usingitems
since the tag in the example is alreadyref
. There may also be race conditions that can be resolved by tracking the status of API calls.