본문 바로가기
웹/React

[React/에러] TypeError: Cannot read properties of undefined (reading 'map')

by ohojee 2023. 9. 11.
Cannot read properties of undefined (reading 'map')
TypeError: Cannot read properties of undefined (reading 'map')

첫 턴에 데이터가 안 들어왔을 때에도 렌더링이 실행된다. 그래서 데이터가 undefined라 생기는 문제인데 다른 블로그를 보니 

return (
    {currentItems.map((item, index) => (
        <GridBox key={index} item={item} gridArea={`gridBox${index % 10 + 1}`} />
    ))}
)

currentItems.map 앞에 currentItems && 을 넣어주면 된다는거였다. 여기서의 핵심은 먼저 and로 연결되어 있기에 currentItems이 존재하면 괄호 안을 실행한다는건데 그러면 아래처럼 위 아래만 뜨고 아무런 결과가 뜨지 않았다.

return 안에서 currentItems를 data.item으로 호출했을 때는 잘 떴다. 왜 떴을까 생각해보니   if (!data) { return null; } 이 부분이 있어서 그랬던 것 같다.

 if (!(data && currentItems)) { return null; }

그래서 이렇게 해보았다.

 
그랬더니 이렇게 잠깐 떴다 사라졌다. 이건 또 왜? openapi는 잘 불러와지는데.
위의 if문에 더해서 currentItems.map 앞에 currentItems && 까지 추가시켜주니 작동했다,, 아까는 안 됐던 것 같은데 뭐지.

 
관련 전체코드는 더보기에

더보기

전체코드

const SearchResultPage = () => {
    const [currentPage, setcurrentPage] = useState(1)
    const [currentArray, setCurrentArray] = useState(0);
    const [totalPage, setTotalPage] = useState([]);
    const [slicePages, setSlicePages] = useState([]);
    const [itemsPerPage, setItemsPerPage] = useState([]);
    const [currentItems, setCurrentItems] = useState([]);
    const pagePerLimit = 10
    const pageArrayLimit = 5
    const maxResults = 50
    
    // 책 데이터 db에 저장
    const [data, setData] = useState(null);
    const [loading, setLoading] = useState(false);
    
    const searchResultFunc = async () => {
        setLoading(true);
        try {
            const result = await axios.get(`ttb/api/ItemSearch.aspx?ttbkey=${process.env.REACT_APP_TTBKEY}&Query=모순&QueryType=Title&MaxResults=${maxResults}&start=${currentArray + 1}&SearchTarget=Book&output=js&Version=20131101`);
            console.log(result.data)
            setData(result.data);
            const newItemSlice = [];
            for (let i = 0; i < maxResults; i += pagePerLimit) {
                newItemSlice.push(result.data.item.slice(i, i + pagePerLimit));
            }
            setItemsPerPage(newItemSlice)
        } catch (e) {
            console.log(e);
        }
        setLoading(false);
    }

    useEffect(() => {
        searchResultFunc();
    }, [currentArray]);

    if (!(data && currentItems)) {
        return null;
    }

    return (
        {currentItems && currentItems.map((item, index) => (
            <GridBox key={index} item={item} gridArea={`gridBox${index % 10 + 1}`} />
        ))}
    )
}

 
 
참고 자료
https://devbirdfeet.tistory.com/47
 

댓글