Middle+
Problems with a timer in the setup() component of Vue with SSR support, which is cleared in onUnmounted.
sobes.tech AI
Answer from AI
When using timers in the setup() of a Vue component with SSR, it is important to consider that there is no DOM on the server and timers may behave differently. If a timer is created in setup() and cleared in onUnmounted, then during server-side rendering, onUnmounted is not called because the component is not mounted in the browser.
Because of this, the timer may not be cleaned up properly, leading to leaks or errors.
Recommendations:
- Check that timer code runs only on the client, for example, using
if (typeof window !== 'undefined'). - Use
onBeforeUnmountoronUnmountedto clear timers, but only on the client side. - For SSR, you can delay creating the timer until the
onMountedhook, which is not called on the server.
Example:
import { onMounted, onUnmounted, ref } from 'vue';
export default {
setup() {
let timer = null;
onMounted(() => {
timer = setInterval(() => {
console.log('tick');
}, 1000);
});
onUnmounted(() => {
clearInterval(timer);
});
}
}
This approach ensures that timers are created and cleared only on the client, avoiding SSR issues.