[55강 메모리 누수 관리] toast timer clear 오류
371
작성한 질문수 1
코지코더님 안녕하세요.
양질에 강의에 감사드리며, 55강을 듣다가 2가지 의문점이 생겨 문의 드립니다.
질문1) toastTimer가 삭제되지 않는 현상
onUnmounted hook에서 toastTimer를 삭제하는 로직의 동작이 강의 내용과 상이하여 문의 드립니다.
강의와 동일하게 소스를 작성하였는데, 콘솔을 보면
onUnmounted
timeout
이 출력됩니다. timeout이 출력되지 않아야 맞는 동작인 것 같은데 왜 clear 되지 않는 걸까요?
_id.vue 전체 소스는 하단에 첨부하였습니다!
const toastTimer = ref(null);
const triggerToast = (message, type = 'success') => {
toastMessage.value = message;
toastType.value = type;
showToast.value = true;
toastTimer.value = setTimeout(() => {
console.log('timeout');
toastMessage.value = '';
toastType.value = '';
showToast.value = false;
}, 3000);
};
onUnmounted(() => {
console.log('onUnmounted');
clearTimeout(toastTimer.value);
});
질문2) timer 변수에 ref를 사용하지 않아도 되는가?
강의에서 const toastTimer = ref(null); 과 같이 timer를 담는 변수에도 ref로 감싸셨는데요,
ref로 감싸지 않고 let 으로 선언하면 안 되나요?
----
<template>
<h2>To-Do Page</h2>
<div v-if="loading">Loading...</div>
<form
v-else
@submit.prevent="onSave">
<div class="row">
<div class="col-6">
<div class="form-group mb-2">
<label class="my-2">Todo Subject</label>
<input type="text" class="form-control" v-model="todo.title">
</div>
<button type="button" class="btn btn-outline-dark">Cancel</button>
<button
type="submit"
class="btn btn-primary ms-2"
:disabled="!todoUpdated"
@click.stop="onSave"
>Save</button>
</div>
<div class="col-6">
<div class="form-group">
<label class="my-2">Status</label>
</div>
<button
type="button"
class="btn btn-primary"
:class="statusBtnClass"
@click="toggleTodoStatus"
>{{ statusBtnLabel }}</button>
</div>
</div>
</form>
<Toast v-if="showToast" :message="toastMessage" :type="toastType"></Toast>
</template>
<script>
import { useRoute } from 'vue-router';
import { ref, computed, onUnmounted } from 'vue';
import _ from 'lodash';
import { getTodoItem, putTodoItem } from '@/api';
import Toast from '@/components/Toast.vue';
export default {
setup() {
const route = useRoute();
const todoId = route.params.id;
const todo = ref(null);
const originTodo = ref(null);
const loading = ref(true);
const showToast = ref(false);
const toastType = ref('success');
const toastMessage = ref('');
const toastTimer = ref(null);
const triggerToast = (message, type = 'success') => {
toastMessage.value = message;
toastType.value = type;
showToast.value = true;
toastTimer.value = setTimeout(() => {
console.log('timeout');
toastMessage.value = '';
toastType.value = '';
showToast.value = false;
}, 3000);
};
onUnmounted(() => {
console.log('onUnmounted');
clearTimeout(toastTimer.value);
});
const getTodo = async () => {
try {
const res = await getTodoItem(todoId);
todo.value = res.data;
originTodo.value = { ...res.data };
loading.value = false;
} catch (err) {
triggerToast('Error occurred!', 'danger');
}
};
const statusBtnClass = computed(() => (todo.value.done ? 'btn-success' : 'btn-danger'));
const statusBtnLabel = computed(() => (todo.value.done ? 'Completed' : 'Incompleted'));
const toggleTodoStatus = () => {
todo.value.done = !todo.value.done;
};
const todoUpdated = computed(() => !_.isEqual(todo.value, originTodo.value));
const onSave = async () => {
try {
const { data } = await putTodoItem(todoId, todo.value);
originTodo.value = { ...data };
triggerToast('Successfully saved!');
} catch (err) {
triggerToast('Error occurred!', 'danger');
}
};
getTodo();
return {
todo,
loading,
statusBtnClass,
statusBtnLabel,
toggleTodoStatus,
todoUpdated,
onSave,
showToast,
toastMessage,
toastType,
};
},
components: {
Toast,
},
};
</script>
<style scoped>
</style>
답변 2
1
질문 1. form 태그에 @submit에서 onSave 함수를 사용하고 있고 button에도 @click에서 onSave를 실행해하고 있습니다. 그래서 setTimeout이 두번 실행되고 clear 할때 하나는 clear 되지 않아서 그런거 같아요.
onSave를 한번만 실행할수 있게 둘중에 하나를 지우시면 잘 작동할거 같네요
질문 2. let 사용하셔도 됩니다
확인해보시고 안되면 또 댓글 남겨주세요 ^^
numberOfPages 결과 nan
0
426
2
todos 질문입니다.
0
295
2
작동은 되긴 하는데 해당 메세지는 왜 뜨는걸까요?
1
376
0
강의노트 문의
0
379
1
x-total-count 및 db.json id값 문제
0
924
1
개발툴 글자체, 크기, 색깔 세팅 문의
0
226
1
onMount 관련 강의가 몇강에 있었죠?ㅠㅠ
0
309
1
json server실행/중지 문의드립니다!
0
486
1
3:53 분에 HelloWorld 태그 인식을 못해서 오류 발생하비낟!
0
471
1
Composition API?
0
397
1
24강에서 computed의 종속성이 변경도록 return하는데, 그러면 computed가 다시 실행되나요?
0
404
1
구조가 다름...
0
488
1
59강 API body 질문입니다.
0
304
1
로그인과 같이 레이아웃이 완전 다른 페이지를 만들때는 router 를 어떻게 할까요?
0
439
1
vue CLI 설치 관련 문의드립니다.
0
594
1
31강 DB질문
0
420
1
to와 :to의 차이점
0
451
1
52강의 originalTpdp ref 와 todo ref
0
555
1
delete todo 함수를 prop으로 내려주지 않는 이유는 무엇인가요??
0
415
1
computed 와 검색 기능 추가 질문드려요.
0
449
1
[33강] pagination2 numberOfPages 호출
0
384
1
리렌더링 관련 질문
0
339
1
배포 관련 질문드립니다.
0
315
1
30강 질문드립니다.
0
224
1





