Vue fetch gets called twice

Viewed 40

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));
  },
});

The fetch gets called twice, and I don't know why. Is there any solution for this?

1 Answers

From the shared code, it looks like the component is getting mounted twice, so you might need to look into the component that is mounting it.

However, you could store the response so the fetch is not made multiple times

const tags = ref(null);
const tagsError = ref(null);
const getTags = () => {
  fetch("http://localhost:3000/tags")
    .then((res) => res.json())
    .then((data) => {
      tags.value = data;
      return tags;
    })
    .catch((err) => tagsError.value = err.message;
}

export default defineComponent({
  name: "filter",
  props: {},
  setup() {
    const states = useCounterStore();
    if(tags.value === null) {
      getTags().then(() => this.items = [...tags.value]);
    } else {
      this.items = [...tags.value];
    }
    return { states };
  },
  data() {
    return {
      items: [],
    };
  },
  methods: {},
});

because tags is declared outside of the component, it will behave like a global, so it will be stateful. Every time the component is setup, it will check whether the tags are loaded then either use the cached data, or load it and update the items after.

A couple notes about the example...
Ideally, such logic would be in a separate file and have better abstraction. For example, if you have multiple APIs they could share this function, eg. const {state, data, error} = useApiCall('/tags'). And instead of using items, because the tags in the example is a ref already, you could use tags directly. There is also a possibility of a race condition that could be solved by tracking the API call state.

Related