-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcart.jsx
210 lines (200 loc) · 5.69 KB
/
cart.jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
// simulate getting products from DataBase
const products = [
{ name: "Apples_:", country: "Italy", cost: 3, instock: 10 },
{ name: "Oranges:", country: "Spain", cost: 4, instock: 3 },
{ name: "Beans__:", country: "USA", cost: 2, instock: 5 },
{ name: "Cabbage:", country: "USA", cost: 1, instock: 8 },
];
//=========Cart=============
const Cart = (props) => {
const { Card, Accordion, Button } = ReactBootstrap;
let data = props.location.data ? props.location.data : products;
console.log(`data:${JSON.stringify(data)}`);
return <Accordion defaultActiveKey="0">{list}</Accordion>;
};
const useDataApi = (initialUrl, initialData) => {
const { useState, useEffect, useReducer } = React;
const [url, setUrl] = useState(initialUrl);
const [state, dispatch] = useReducer(dataFetchReducer, {
isLoading: false,
isError: false,
data: initialData,
});
console.log(`useDataApi called`);
useEffect(() => {
console.log("useEffect Called");
let didCancel = false;
const fetchData = async () => {
dispatch({ type: "FETCH_INIT" });
try {
const result = await axios(url);
console.log("FETCH FROM URl");
if (!didCancel) {
dispatch({ type: "FETCH_SUCCESS", payload: result.data });
}
} catch (error) {
if (!didCancel) {
dispatch({ type: "FETCH_FAILURE" });
}
}
};
fetchData();
return () => {
didCancel = true;
};
}, [url]);
return [state, setUrl];
};
const dataFetchReducer = (state, action) => {
switch (action.type) {
case "FETCH_INIT":
return {
...state,
isLoading: true,
isError: false,
};
case "FETCH_SUCCESS":
return {
...state,
isLoading: false,
isError: false,
data: action.payload,
};
case "FETCH_FAILURE":
return {
...state,
isLoading: false,
isError: true,
};
default:
throw new Error();
}
};
const Products = (props) => {
const [items, setItems] = React.useState(products);
const [cart, setCart] = React.useState([]);
const [total, setTotal] = React.useState(0);
const {
Card,
Accordion,
Button,
Container,
Row,
Col,
Image,
Input,
} = ReactBootstrap;
// Fetch Data
const { Fragment, useState, useEffect, useReducer } = React;
const [query, setQuery] = useState("http://localhost:1337/api/products");
const [{ data, isLoading, isError }, doFetch] = useDataApi(
"http://localhost:1337/api/products",
{
data: [],
}
);
console.log(`Rendering Products ${JSON.stringify(data)}`);
// Fetch Data
const addToCart = (e) => {
let name = e.target.name;
let item = items.filter((item) => item.name == name);
console.log(`add to Cart ${JSON.stringify(item)}`);
setCart([...cart, ...item]);
//doFetch(query);
};
const deleteCartItem = (index) => {
let newCart = cart.filter((item, i) => index != i);
setCart(newCart);
};
const photos = ['apple.png', 'orange.png', 'beans.png', 'cabbage.png'];
let list = items.map((item, index) => {
//let n = index + 1049;
//let url = "https://picsum.photos/id/" + n + "/50/50";
return (
<li key={index}>
<Image src={photos[index % 4]} height={70 } width={70} roundedCircle></Image>
<Button variant="primary" size="large">
{item.name}:{item.cost}
</Button>
<input name={item.name} type="submit" onClick={addToCart}></input>
</li>
);
});
let cartList = cart.map((item, index) => {
return (
<Accordion.Item key={1+index} eventKey={1 + index}>
<Accordion.Header>
{item.name}
</Accordion.Header>
<Accordion.Body onClick={() => deleteCartItem(index)}
eventKey={1 + index}>
$ {item.cost} from {item.country}
</Accordion.Body>
</Accordion.Item>
);
});
let finalList = () => {
let total = checkOut();
let final = cart.map((item, index) => {
return (
<div key={index} index={index}>
{item.name}
</div>
);
});
return { final, total };
};
const checkOut = () => {
let costs = cart.map((item) => item.cost);
const reducer = (accum, current) => accum + current;
let newTotal = costs.reduce(reducer, 0);
console.log(`total updated to ${newTotal}`);
return newTotal;
};
// TODO: implement the restockProducts function
const restockProducts = (url) => {
doFetch(url);
let newItems = data.map((item) => {
let {name, country, cost, instock} = item;
return {name, country, cost, instock};
});
setItems([...items, ...newItems]);
};
return (
<Container>
<Row>
<Col>
<h1>Product List</h1>
<ul style={{ listStyleType: "none" }}>{list}</ul>
</Col>
<Col>
<h1>Cart Contents</h1>
<Accordion defaultActiveKey="0">{cartList}</Accordion>
</Col>
<Col>
<h1>CheckOut </h1>
<Button onClick={checkOut}>CheckOut $ {finalList().total}</Button>
<div> {finalList().total > 0 && finalList().final} </div>
</Col>
</Row>
<Row>
<form
onSubmit={(event) => {
restockProducts(`http://localhost:1337/${query}`);
console.log(`Restock called on ${query}`);
event.preventDefault();
}}
>
<input
type="text"
value={query}
onChange={(event) => setQuery(event.target.value)}
/>
<button type="submit">ReStock Products</button>
</form>
</Row>
</Container>
);
};
// ========================================
ReactDOM.render(<Products />, document.getElementById("root"));