[오류해결] TypeError: Cannot read properties of undefined (reading '...')

Yeong·2023년 4월 14일
0

문제점

Redux를 이용하여 값을 가져오는 과정에서 console창에도 데이터가 찍히고, 실제 웹에도 값이 출력되나 이내 Cannot read properties of undefined 이라는 창이 계속 떴다.

원인 :

해결방법

Optional chaining 연산자 사용

'?'는 중첩된 속성에 접근할 때 유용하며, 중간에 속성이 존재하지 않는 경우에도 오류를 막을 수 있다. 이를 통해 Redux store에서 데이터를 가져올 때 발생할 수 있는 "TypeError: Cannot read properties of undefined (reading '...')"와 같은 오류를 해결할 수 있다.

실제 코드 (오류났던 코드)

const useremail = useSelector((state)=> state.user.userData.email);

에서 연산자를 추가하여

const userEmail = useSelector((state) => state.user?.userData?.email); 

이라고 작성해줬다.
=> user, userData, 그리고 email 속성에 접근하고있다. 각각의 속성이 존재하지 않는 경우에는 undefined가 반환되어 오류가 발생하지 않는다.

연산자 사용예시

const user = {
  name: "John",
  // email 속성이 존재하지 않는 경우도 있음
};

// Optional chaining 연산자를 사용하여 email 속성에 접근하고,
// 속성이 존재하지 않는 경우 undefined를 반환
const userEmail = user?.email;

0개의 댓글