js reduce 에러해결 Cannot read properties of undefined (reading 'push')

바람찬허파·2023년 1월 28일
0

🚨 문제상황

familyMember = ["C3jdEF2cyveDYiTJsLI4UUmbfxG2", 가족2ID, ...] 가족 마다 고유한 ID가 담긴 배열이 있고,
하나의 ID를

[ {id: "C3jdEF2cyveDYiTJsLI4UUmbfxG2", userName: 이지수}, {id : ...} , ]

같은 형태로 변형하고자 했다 (userName은 DB에서 조회하는 형태)

map함수에서 return 값을 넘기는 데에 실패해서
reduce함수를 사용해 cur의 id를 통해 -> userName을 찾고 -> {id:, userName: }의 형태로 변환-> acc에 저장의 순서로 진행하고자 했다. 그러나, 마지막 단계에서 acc.push({id:, userName : })에서 에러가 생겼다.

        snapshot.data().family_member.reduce((acc, cur, index) => {
          UserClientCollection.doc(cur)
            .get()
            .then(doc => {
              acc.push(doc.data().userName)
              console.log(acc)
            });
        }, []);
        
        

에러메시지

Main.js:1 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'push')
at eval

🛠️ 문제 해결

그러던 중 reduce + 에러 메시지로 찾은 stackoverflow글이 도움이 되었다 .
나 또한 질문 작성자처럼 에러 메시지를 acc 라는 배열에 push 가 제공되지 않는다는 것으로 이해했고,
(vscode에서도 push 함수 추천이 뜨지 않았기에,) 그 이유에 대해 찾고 있었다.

허나 끙끙 거렸던 것에 비하여 솔루션은 간단했다.
return acc 를 통해 push했던 acc를 리턴해주어야한다는 것이다 .
만약 return 해주지 않는다면, undefined를 리턴하기에 다음 요소에서 acc.push()를 할 때 push를 쓸 수 없다는 에러가 뜬다. (즉, acc가 undefined 되는 것이 문제!)

cosnole.log(acc)를 찍어보았을 때, 첫 요소는 acc 안에 push되는지에 대해 의문이 있었는데,
앞선 내용을 이해하고 나니 비로소 설명이 되었다.

앞선 솔루션으로 변환한 코드는

snapshot.data().family_member.reduce((acc, cur) => {
          UserClientCollection.doc(cur)
            .get()
            .then(doc => {
              acc.push({
                id: cur,
                userName: doc.data().userName,
              });
              console.log(acc)
            });
            return (acc) // <-- 이 부분을 추가하였다
        }, []);

👀 수정완료


다음과 같이 acc에 모든 family_member의 id와 이름이 push 된 것을 볼 수 있다.


📖 출처

https://stackoverflow.com/questions/68215028/cannot-read-property-push-of-undefined-in-javascript
(reduce 함수와 map 함수에 대해 전반적 이해도를 높일 수 있었다. 더 자세히 읽어보아도 충분할 듯! ) https://www.zerocho.com/category/JavaScript/post/5acafb05f24445001b8d796d
https://velog.io/@ylyl/TIL-will-be-no-error-in-JS

0개의 댓글