CodexBloom - Programming Q&A Platform

Vue 3: How to prevent duplicate API calls on component re-renders with v-if?

πŸ‘€ Views: 0 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-17
vuejs api v-if performance vue

I'm collaborating on a project where I've been researching this but I'm working on a Vue 3 application and I've run into an scenario where my component is making duplicate API calls when it re-renders due to a `v-if` condition..... I have a child component that fetches data from an API when it mounts. However, if the parent component's state changes and the child is conditionally rendered using `v-if`, it seems to trigger the API call again, even if the data hasn't changed. Here’s a simplified version of my code: ```vue <template> <div> <button @click="toggleChild">Toggle Child Component</button> <ChildComponent v-if="showChild" :someProp="someValue" /> </div> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent }, data() { return { showChild: false, someValue: 'initial', }; }, methods: { toggleChild() { this.showChild = !this.showChild; }, }, }; </script> ``` And in my `ChildComponent`, I have something like this: ```vue <template> <div> Loading... </div> </template> <script> import { onMounted } from 'vue'; export default { props: ['someProp'], setup(props) { onMounted(() => { fetchData(); }); function fetchData() { fetch(`https://api.example.com/data?query=${props.someProp}`) .then(response => response.json()) .then(data => { console.log(data); }) .catch(behavior => console.behavior('API behavior:', behavior)); } }, }; </script> ``` I tried using a `keep-alive` wrapper around the `ChildComponent`, but that didn't seem to help. Additionally, I’ve looked into managing the state in a global store like Pinia, but it feels like overkill for this scenario. Is there a way to prevent the API call from being made again when the child component re-mounts? Should I cache the API response somehow or maybe debounce the API call? Any suggestions would be greatly appreciated! This is my first time working with Vue 3.11. What would be the recommended way to handle this? My team is using Vue for this REST API. Thanks in advance!