/
ProductListScreen.jsx
115 lines (106 loc) · 3.31 KB
/
ProductListScreen.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
import { LinkContainer } from 'react-router-bootstrap';
import { Table, Button, Row, Col } from 'react-bootstrap';
import { FaEdit, FaPlus, FaTrash } from 'react-icons/fa';
import { useParams } from 'react-router-dom';
import Message from '../../components/Message';
import Loader from '../../components/Loader';
import Paginate from '../../components/Paginate';
import {
useGetProductsQuery,
useDeleteProductMutation,
useCreateProductMutation,
} from '../../slices/productsApiSlice';
import { toast } from 'react-toastify';
const ProductListScreen = () => {
const { pageNumber } = useParams();
const { data, isLoading, error, refetch } = useGetProductsQuery({
pageNumber,
});
const [deleteProduct, { isLoading: loadingDelete }] =
useDeleteProductMutation();
const deleteHandler = async (id) => {
if (window.confirm('Are you sure')) {
try {
await deleteProduct(id);
refetch();
} catch (err) {
toast.error(err?.data?.message || err.error);
}
}
};
const [createProduct, { isLoading: loadingCreate }] =
useCreateProductMutation();
const createProductHandler = async () => {
if (window.confirm('Are you sure you want to create a new product?')) {
try {
await createProduct();
refetch();
} catch (err) {
toast.error(err?.data?.message || err.error);
}
}
};
return (
<>
<Row className='align-items-center'>
<Col>
<h1>Products</h1>
</Col>
<Col className='text-end'>
<Button className='my-3' onClick={createProductHandler}>
<FaPlus /> Create Product
</Button>
</Col>
</Row>
{loadingCreate && <Loader />}
{loadingDelete && <Loader />}
{isLoading ? (
<Loader />
) : error ? (
<Message variant='danger'>{error.data.message}</Message>
) : (
<>
<Table striped bordered hover responsive className='table-sm'>
<thead>
<tr>
<th>ID</th>
<th>NAME</th>
<th>PRICE</th>
<th>CATEGORY</th>
<th>BRAND</th>
<th></th>
</tr>
</thead>
<tbody>
{data.products.map((product) => (
<tr key={product._id}>
<td>{product._id}</td>
<td>{product.name}</td>
<td>${product.price}</td>
<td>{product.category}</td>
<td>{product.brand}</td>
<td>
<LinkContainer to={`/admin/product/${product._id}/edit`}>
<Button variant='light' className='btn-sm mx-2'>
<FaEdit />
</Button>
</LinkContainer>
<Button
variant='danger'
className='btn-sm'
onClick={() => deleteHandler(product._id)}
>
<FaTrash style={{ color: 'white' }} />
</Button>
</td>
</tr>
))}
</tbody>
</Table>
<Paginate pages={data.pages} page={data.page} isAdmin={true} />
</>
)}
</>
);
};
export default ProductListScreen;