아래 코드로 해보면 문제는 맵 함수의 Remove Product 함수를 호출하는 부분에 있습니다.
function AddOrder() {
const d = new Date();
let text = d.toString();
const [addOrder] = useMutation(queries.ADD_ORDER);
const [editUser] = useMutation(queries.EDIT_USER_CART);
const [editProduct] = useMutation(queries.EDIT_PRODUCT);
function RemoveProduct (x) {
let getProd = useQuery(queries.GET_PRODUCTS_BY_ID, {
fetchPolicy: "network-only",
variables: {
_id : x._id
},
});
console.log(getProd.quantity)
console.log(x.quantity)
let a = getProd.quantity - x.quantity
console.log(a)
editProduct({
variables: {
_id : x._id,
quantity: a
},
});
return null;
}
const { currentUser } = useContext(AuthContext);
if (error) {
return <h1> error</h1>;
} else if (loading) {
return <h1> loading</h1>;
} else if (data && getUserOrders.data && currentUser && data.getUser.cart.length > 0) {
let newCart = [];
let total = 0;
for (let i = 0; i < data.getUser.cart.length; i++) {
total += data.getUser.cart[i].price * data.getUser.cart[i].quantity;
newCart.push({
orderedQuantity: data.getUser.cart[i].quantity,
_id: data.getUser.cart[i]._id,
name: data.getUser.cart[i].name,
image: data.getUser.cart[i].image,
price: data.getUser.cart[i].price,
});
}
newCart.map((x) => RemoveProduct(x))
editUser({
variables: {
id: currentUser.uid,
cart: [],
},
});
}
}
export default AddOrder;
이 코드를 실행해보면 아래와 같은 에러가 뜨는데요.
이걸 어떻게 해결할 수 있나요?
Remove Products에 대한 별도의 component를 만들고 이 함수를 호출하려고 했지만 역시 작동하지 않습니다.
javascript reactjs
https://reactjs.org/docs/hooks-overview.html#rules-of-hooks
여기 글을 참조해보시면 되는데 요약하면
1. 최상위 레벨에서만 hook를 호출해라.
2. 루프, 조건 또는 중첩 함수 내부에서 hook를 호출하지 말아라.
3. 다른 리턴값 이전에 리액트 function의 최상위 레벨에서 항상 hook를 사용해야 한다.
4. React function component 또는 사용자 지정 hook에서만 호출 hook를 호출할 수 있다.
결론은 RemoveProduct function을 중첩하거나 그 안에서 hook를 제거하면 안됩니다.
© 2023 OneMinuteCode. All rights reserved.