UNPKG

4.2 kBJavaScriptView Raw
1import { useApolloClient } from '@apollo/react-hooks';
2import { CartIdContext } from '@jetshop/core/components/Cart/CartIdContext';
3import { useContext, useState } from 'react';
4import throwErrorInDev from '../helpers/throwErrorInDev';
5export function useAddMultipleToCart(items, hookQueries, hookCallbacks) {
6 const client = useApolloClient();
7 const [status, setStatus] = useState('idle');
8 const [data, setData] = useState();
9 const { cartId, setCartId } = useContext(CartIdContext);
10 if (!items) {
11 throwErrorInDev(true, `You must pass an array of products to useAddMultipleToCart`);
12 return null;
13 }
14 function updateCart({ data }) {
15 const cartIdNotSet = !cartId;
16 const cartIdFromMutation = data.addMultipleToCart.cart.id;
17 const newCartIdReturnedFromAPI = cartIdFromMutation !== cartId;
18 // Set the cart ID in context so any future add to cart actions use the same
19 // ID
20 if (cartIdNotSet || newCartIdReturnedFromAPI) {
21 setCartId(cartIdFromMutation);
22 }
23 }
24 function addMultiple(q, cbs) {
25 const queries = hookQueries || q;
26 const callbacks = hookCallbacks || cbs;
27 if (!queries || !queries.addMultipleToCartMutation || !queries.cartQuery) {
28 return Promise.reject(`You must pass cartQuery and addMultipleToCartMutation to useAddMultipletoCart or to the addMultiple fn`);
29 }
30 setStatus('loading');
31 return client
32 .mutate({
33 mutation: queries.addMultipleToCartMutation,
34 errorPolicy: 'all',
35 variables: {
36 cartId,
37 items: items.map(({ articleNumber, quantity, comments, configurationIds, preOrderDate }) => ({
38 articleNumber,
39 quantity,
40 comments,
41 configurationIds,
42 preOrderDate
43 }))
44 },
45 refetchQueries: resp => {
46 // When errors are present, the cart does not get automatically
47 // updated. We have to use refetchQueries in that case.
48 return (resp.errors && [{ query: queries.cartQuery, variables: { cartId } }]);
49 }
50 })
51 .then(resp => {
52 setData(resp);
53 (callbacks === null || callbacks === void 0 ? void 0 : callbacks.onCompleted) && callbacks.onCompleted(resp);
54 // Update the cart context
55 updateCart(resp);
56 if (resp.errors) {
57 setStatus('partialFailure');
58 (callbacks === null || callbacks === void 0 ? void 0 : callbacks.onPartialFailure) && callbacks.onPartialFailure(resp);
59 }
60 else {
61 setStatus('success');
62 }
63 return resp;
64 })
65 .catch(err => {
66 console.log('error!', err);
67 setStatus('error');
68 (callbacks === null || callbacks === void 0 ? void 0 : callbacks.onError) && callbacks.onError(err);
69 // TODO: We have to type cast the response until this is fixed in
70 // react-apollo 3.2.0
71 // https://github.com/apollographql/react-apollo/commit/a3dd7e64403de32e9048b2ebd5eb63e14d73cf26
72 });
73 }
74 // If some of the items failed, create a Map containing those items as the key.
75 // The errors returned from the API give us the index of failed items as they
76 // appeared in the mutation's input, so we can use that to create the Map.
77 // We also set the error code as the value
78 const failedItems = new Map();
79 if (status === 'partialFailure') {
80 for (const error of data.errors) {
81 const item = items[error.extensions.data.index];
82 failedItems.set(item, error.extensions.code);
83 }
84 }
85 // code: error.extensions.code
86 // Maintain the same basic interface as `useMutation`.
87 return [
88 addMultiple,
89 {
90 loading: status === 'loading',
91 called: status !== 'idle',
92 error: status === 'error',
93 data,
94 failedItems
95 }
96 ];
97}
98//# sourceMappingURL=useAddMultipleToCart.js.map
\No newline at end of file