• 카테고리

    질문 & 답변
  • 세부 분야

    프론트엔드

  • 해결 여부

    해결됨

axios 컴포저블2 에서 useAxios에서 전달받은 resp값이 null로 나옵니다

24.02.22 14:00 작성 조회수 100

0

useAxios.js 내 axios 연결 .then에서

const resp = ref(null);
//생략
.then(result => {
	resp.value = result;
	data.value = result.data;
})

이렇게 전달을 주면 postList.vue에서

const totalCount = computed(() => resp.value.headers['x-total-count']);

이렇게 받아오면 cannot read properties of undefined 'x-total-count' 이렇게 콘솔창에 x-total-count를 읽을수가 없다고 나와 콘솔에 resp.value를 해보니 null 이 찍혔습니다. 하여 useAxios.js에서

.then(result => {
				resp.value = result;
				resp.value = resp.value.headers['x-total-count'];
				data.value = result.data;
			})

resp에 x-total-count를 넣고

postList.vue에서

const { data: posts, resp: totalCount } = useAxios('/posts', {
	method: 'get',
	params,
});

구조분해?할당으로 totalCount에 넣으니 동작이 되었는데 원인을 알 수 있을까요..

답변 1

답변을 작성해보세요.

0

안녕하세요 🙂

resp.value 값이 null 또는 undefined 일 때 headers 속성에 접근해서 오류가 발생한 거 같은데요.

const totalCount = computed(() => resp.value?.headers['x-total-count'] || 0);

위와 같이 ? 옵셔널 연산자와 기본 값을 사용해서 오류를 피할 수 있을 것 같아요!

casyou1450님의 프로필

casyou1450

질문자

2024.02.23

감사합니다