Middle
Your resume mentions handling race conditions via AbortController. How exactly do you integrate request cancellation into the Vue component lifecycle? For example, if a user leaves the page before the request completes, how do you implement this with complex Pinia logic?
sobes.tech AI
Answer from AI
To prevent race conditions and memory leaks when canceling requests in Vue using Pinia and AbortController, you can do the following:
- Create an instance of
AbortControllerin the component during mounting. - Pass the
signalfrom this controller to fetch/Axios before sending the request. - Call
abort()in thebeforeUnmounthook to cancel all unfinished requests. - If the logic is complex and requests are initiated from Pinia, you can store the
AbortControllerin the store's state or pass it to actions.
Example:
import { defineComponent, onBeforeUnmount } from 'vue'
import { useStore } from '@/stores/myStore'
export default defineComponent({
setup() {
const store = useStore()
const controller = new AbortController()
store.fetchData({ signal: controller.signal })
onBeforeUnmount(() => {
controller.abort() // cancel the request when leaving the page
})
}
})
In Pinia:
import { defineStore } from 'pinia'
import axios from 'axios'
export const useStore = defineStore('main', {
actions: {
async fetchData({ signal }) {
try {
const response = await axios.get('/api/data', { signal })
this.data = response.data
} catch (e) {
if (axios.isCancel(e)) {
console.log('Request canceled')
} else {
throw e
}
}
}
}
})
This approach guarantees that when the user leaves the page, all unfinished requests will be canceled, preventing race conditions and unnecessary state updates.