어쩌다 알게 된 ƪ(•̃͡•̃͡ ƪ

🟦 [React] Uncaught TypeError: Cannot read properties of undefined (reading 'filter') 본문

개발/🟦 React

🟦 [React] Uncaught TypeError: Cannot read properties of undefined (reading 'filter')

비니_ 2025. 3. 23. 12:08
728x90

🚫 에러 내용 🚫

Uncaught TypeError: Cannot read properties of undefined (reading 'filter')

 

 

const filteredData = {
    ...tabData,
    [tabDataKey]: tabData[tabDataKey].filter(item =>
        JSON.stringify(item).toLowerCase().includes(keyword)
    )
}

❓ 오류난 이유❓

 

=> tabData[tabDataKey]가 undefined이거나 null일 때 filter 메서드를 호출하면 오류가 발생

=> tabData[tabDataKey]가 undefined이면 그 위에서 filter()를 호출할 수 없어서 타입 오류가 발생

 

 

📚 해결방법 📚

=> tabData[tabDataKey] && tabData[tabDataKey].filter()

&&를 붙이고 한번 더 해줬더니 에러내용이 없어졌다.

const filteredData = {
    ...tabData,
    [tabDataKey]: tabData[tabDataKey] && tabData[tabDataKey].filter(item =>
        JSON.stringify(item).toLowerCase().includes(keyword)
    )
}

 

 해결된 이유❓

=> tabData[tabDataKey]가 undefined이거나 null이면 && 뒤의 filter()를 실행하지 않음

=> filter()는 undefined가 아니라 false처럼 처리되고, filteredData는 undefined 대신에 false가 들어감

 

=> 옵셔널 체이닝과 비슷하게 동작하지만, 조금 더 명시적인 방식으로 undefined 체크

 

📚 해결방법 2 📚

=> 옵셔널 체이닝 사용

const filteredData = {
    ...tabData,
    [tabDataKey]: tabData[tabDataKey]?.filter(item =>
        JSON.stringify(item).toLowerCase().includes(keyword)
    )
}

 

=> tabData[tabDataKey]가 undefined나 null일 경우 filter()가 자동으로 실행되지 않게 되고, filteredData는 undefined나 null 대신 [](빈 배열)을 반환

 

 

생각하니 에러는 안나지만 내가 구현하고 싶은 부분은 나오지 않고 있따..

다시 짜야지..

그치만 에러나는 이유는 알았다..!

728x90
Comments