프로젝트/딴짓 추적표

[프로젝트] 딴짓추적표 | 트러블슈팅-Cannot read properties of null

paintover23 2023. 9. 20. 17:43
728x90

(진행배경) 아래 코드와 같이 localStorage에서 데이터 파싱을 시도하자 위와 같은 cannot read properties of null(reading 'notes')  에러가 나타났다. 'notes' 값을 읽어오지 못하고 있는 것이다.

// 파싱한 데이터를 화면에 그리기
function showNotes() {
  const showData = parseSavedData();
  console.log('showData', showData);
  
    for (let i = 0; i < showData.notes.length; i++) {
      const note = showData.notes[i];
      const solution = showData.solutions[i];
      const select = showData.selects[i];
      createNote(note, solution, select);
    }
}

showNotes();

 

[문제- Cannot read properties of null.. 에러]

(문제원인) "null"은 자바스크립트에서 사용되는 특별한 값 중 하나로, 값이 없음을 나타낸다. 변수나 속성이 "null" 값을 가지면 해당 변수나 속성은 비어있거나 아무런 값을 가지고 있지 않음을 의미한다. 따라서 "Cannot read properties of null" 오류는 특정 속성이나 변수가 값을 가지고 있지 않고 "null"인 상황에서 해당 값을 읽으려고 발생하는 오류이다. 

 

따라서, 로컬스토리지에 저장된 값(notes)이 없는 초기 화면에서는 데이터가 "null" 이기 때문에 이에 대한 처리를 할 수 없어 에러가 발생한 것이다.

 

(해결방법) 이 문제를 해결하기 위해, 

  • showData가 null이 아닌 경우에만 for 루프를 실행하여 메모를 생성하는 처리를 진행하고, 
  • showData null 경우에는 "저장된 메모 없음" 오류 메시지를 콘솔에 출력시켜 처리를 중단해 "Cannot read properties of null" 오류를 방지하였다.

정상작동

코드는 다음과 같다.

  // showData가 null이 아닌 경우에만 처리
  if (showData) {
    for (let i = 0; i < showData.notes.length; i++) {
      const note = showData.notes[i];
      const solution = showData.solutions[i];
      const select = showData.selects[i];
      createNote(note, solution, select);
    }
  } else {
    //showData null 이면 콘솔 오류 출력하고 처리 종료
    console.error('저장된 메모 없음');
  }

 

 

728x90
반응형