forked from basir/next-amazona
-
Notifications
You must be signed in to change notification settings - Fork 0
/
[slug].js
260 lines (251 loc) · 7.69 KB
/
[slug].js
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
import React, { useContext, useEffect, useState } from 'react';
import NextLink from 'next/link';
import Image from 'next/image';
import {
Grid,
Link,
List,
ListItem,
Typography,
Card,
Button,
TextField,
CircularProgress,
} from '@material-ui/core';
import Rating from '@material-ui/lab/Rating';
import Layout from '../../components/Layout';
import useStyles from '../../utils/styles';
import Product from '../../models/Product';
import db from '../../utils/db';
import axios from 'axios';
import { Store } from '../../utils/Store';
import { getError } from '../../utils/error';
import { useRouter } from 'next/router';
import { useSnackbar } from 'notistack';
export default function ProductScreen(props) {
const router = useRouter();
const { state, dispatch } = useContext(Store);
const { userInfo } = state;
const { product } = props;
const classes = useStyles();
const { enqueueSnackbar } = useSnackbar();
const [reviews, setReviews] = useState([]);
const [rating, setRating] = useState(0);
const [comment, setComment] = useState('');
const [loading, setLoading] = useState(false);
const submitHandler = async (e) => {
e.preventDefault();
setLoading(true);
try {
await axios.post(
`/api/products/${product._id}/reviews`,
{
rating,
comment,
},
{
headers: { authorization: `Bearer ${userInfo.token}` },
}
);
setLoading(false);
enqueueSnackbar('Review submitted successfully', { variant: 'success' });
fetchReviews();
} catch (err) {
setLoading(false);
enqueueSnackbar(getError(err), { variant: 'error' });
}
};
const fetchReviews = async () => {
try {
const { data } = await axios.get(`/api/products/${product._id}/reviews`);
setReviews(data);
} catch (err) {
enqueueSnackbar(getError(err), { variant: 'error' });
}
};
useEffect(() => {
fetchReviews();
}, []);
if (!product) {
return <div>Product Not Found</div>;
}
const addToCartHandler = async () => {
const existItem = state.cart.cartItems.find((x) => x._id === product._id);
const quantity = existItem ? existItem.quantity + 1 : 1;
const { data } = await axios.get(`/api/products/${product._id}`);
if (data.countInStock < quantity) {
window.alert('Sorry. Product is out of stock');
return;
}
dispatch({ type: 'CART_ADD_ITEM', payload: { ...product, quantity } });
router.push('/cart');
};
return (
<Layout title={product.name} description={product.description}>
<div className={classes.section}>
<NextLink href="/" passHref>
<Link>
<Typography>back to products</Typography>
</Link>
</NextLink>
</div>
<Grid container spacing={1}>
<Grid item md={6} xs={12}>
<Image
src={product.image}
alt={product.name}
width={640}
height={640}
layout="responsive"
></Image>
</Grid>
<Grid item md={3} xs={12}>
<List>
<ListItem>
<Typography component="h1" variant="h1">
{product.name}
</Typography>
</ListItem>
<ListItem>
<Typography>Category: {product.category}</Typography>
</ListItem>
<ListItem>
<Typography>Brand: {product.brand}</Typography>
</ListItem>
<ListItem>
<Rating value={product.rating} readOnly></Rating>
<Link href="#reviews">
<Typography>({product.numReviews} reviews)</Typography>
</Link>
</ListItem>
<ListItem>
<Typography> Description: {product.description}</Typography>
</ListItem>
</List>
</Grid>
<Grid item md={3} xs={12}>
<Card>
<List>
<ListItem>
<Grid container>
<Grid item xs={6}>
<Typography>Price</Typography>
</Grid>
<Grid item xs={6}>
<Typography>${product.price}</Typography>
</Grid>
</Grid>
</ListItem>
<ListItem>
<Grid container>
<Grid item xs={6}>
<Typography>Status</Typography>
</Grid>
<Grid item xs={6}>
<Typography>
{product.countInStock > 0 ? 'In stock' : 'Unavailable'}
</Typography>
</Grid>
</Grid>
</ListItem>
<ListItem>
<Button
fullWidth
variant="contained"
color="primary"
onClick={addToCartHandler}
>
Add to cart
</Button>
</ListItem>
</List>
</Card>
</Grid>
</Grid>
<List>
<ListItem>
<Typography name="reviews" id="reviews" variant="h2">
Customer Reviews
</Typography>
</ListItem>
{reviews.length === 0 && <ListItem>No review</ListItem>}
{reviews.map((review) => (
<ListItem key={review._id}>
<Grid container>
<Grid item className={classes.reviewItem}>
<Typography>
<strong>{review.name}</strong>
</Typography>
<Typography>{review.createdAt.substring(0, 10)}</Typography>
</Grid>
<Grid item>
<Rating value={review.rating} readOnly></Rating>
<Typography>{review.comment}</Typography>
</Grid>
</Grid>
</ListItem>
))}
<ListItem>
{userInfo ? (
<form onSubmit={submitHandler} className={classes.reviewForm}>
<List>
<ListItem>
<Typography variant="h2">Leave your review</Typography>
</ListItem>
<ListItem>
<TextField
multiline
variant="outlined"
fullWidth
name="review"
label="Enter comment"
value={comment}
onChange={(e) => setComment(e.target.value)}
/>
</ListItem>
<ListItem>
<Rating
name="simple-controlled"
value={rating}
onChange={(e) => setRating(e.target.value)}
/>
</ListItem>
<ListItem>
<Button
type="submit"
fullWidth
variant="contained"
color="primary"
>
Submit
</Button>
{loading && <CircularProgress></CircularProgress>}
</ListItem>
</List>
</form>
) : (
<Typography variant="h2">
Please{' '}
<Link href={`/login?redirect=/product/${product.slug}`}>
login
</Link>{' '}
to write a review
</Typography>
)}
</ListItem>
</List>
</Layout>
);
}
export async function getServerSideProps(context) {
const { params } = context;
const { slug } = params;
await db.connect();
const product = await Product.findOne({ slug }, '-reviews').lean();
await db.disconnect();
return {
props: {
product: db.convertDocToObj(product),
},
};
}