[에러] TypeError: randomArray is not iterable

이효린·2023년 5월 19일
0

Error

목록 보기
4/8

TypeError: randomArray is not iterable

뭐지 이거 왜 iterable이 아니지..?

내가 계획한 대로라면 randomArray는 배열이기때문에 iterable 객체여야한다. 뭔가 이상하다..

코드를 한번 봐보자

코드 흐름을 보면

try {
      const response = await axios.get(`https://api.hipspot.xyz/cafe/`); //(1) api호출
      const { data } = response; // (2) response 중 data만 객체분해할당
      const cafeIds = data && data.items.map((cafe: CafeData) => cafe.cafeId); //(3) 그 data 중 cafeId만 가져와서 새로운 배열로 만든다.
			const randomArray = cafeIds[Math.floor(Math.random() * cafeIds.length)]; //(4) 새로 만든 cafeId를 랜덤으로 돌리고 새로운 배열에 넣는다.
      const [randomCafeId] = randomArray; // (5) 그 새 배열에서 객체분해할당을 하여 첫 번째 요소만 가져와 출력해낸다.
      console.log(randomCafeId);
    } catch (error) {
      console.error(error);
    }

그렇다면 (1), (2), (3), (4) 중 어딘가가 잘못됐을텐데..

하나하나 콘솔에 찍어보았다.

  1. response 콘솔

  2. data 콘솔

  3. cafeIds 콘솔

    뭔가 이상하다. 왜 undefined지 ?

    여기서 에러가 발생한건가? 다시 코드를 읽어보았다.

    const cafeIds = data && data.items.map((cafe: CafeData) => cafe.cafeId); 

    오잉 data 안에 properties안에 cafeId가 있는건데 map 함수 내에서 cafeId를 참조할 때 cafe.cafeId로 참조한다.

    그럼 cafe.properties.cafeId로 바꿔보자 !

    const cafeIds = data && data.map((*cafe*: any) => *cafe*.properties.cafeId);

    해결 완료 !

    💡 뭔가 제대로 작동 안하면 콘솔에 한 번 찍어보자 ! data 구조도 잘 보자 !!

0개의 댓글