MVC를 복습하던 중,배열인 객체를 controller가 models에 전달하여,
map으로 params에 넣은 다음 한번의 쿼리로 테이블에 Insert into 하려고 하였다.
contorller에서 models에 전달한 객체는 아래와 같다.
"orders": [
{
"quantity": 1,
"itemId": 2
},
...
]
const params= orders.map((order)=>
[order.quantity, order.itemId])
이렇게 params에 담아 아래와 같이 쿼리를 보내려고 하였다.
INSERT INTO orders (order_quantity,item_id) VALUES ?
그런데 Uncaught TypeError: Cannot read properties of undefined (reading 'map')
라는 오류 메시지를 만났다.
구글링해보니, React는 orders.map(...)을 반복실행할 때 첫 턴에 데이터가 아직 안들어와도 렌더링이 실행되며 당연히 그 데이터는 undefined로 정의되어 오류가 난다는 것이다.
그래서 orders.map 앞에 &&
연산자를 사용한다고 한다.
orders && orders.map((order)=>[order.quantity, order.itemId])
라고 수정하니 해결되었다!
JavaScript에서 true && expression은 두 조건 모두 만족해야지 실행되기 때문이다.