2023-04-18 21:06:26 +04:00

92 lines
3.4 KiB
JavaScript

import React, {useState} from 'react';
const productModel ={
name: '',
cost: ''
}
export default function ProductPage(){
const mainUrl = 'http://localhost:8080/product/'
const [product, setProduct] = useState(productModel)
const [products, setProducts] = useState([])
const addProduct = (e) => {
e.preventDefault()
setProducts((prevState) => [...prevState, product])
setProduct(productModel)
}
const getAllProducts = () =>{
fetch(`${mainUrl}`)
.then((res) => {
return res.json();
})
.then((arr) => {
setProducts(arr);
})
}
return(
<div className="container">
<form id="form" onSubmit={addProduct}>
<div className="row mt-3">
<div className="col-sm-6">
<label for="lastName" className="form-label">Наименование</label>
<input type="text" className="form-control" id="productName" required
onChange={(e) => setProduct((prevState => (
{
...prevState, name: e.target.value
}
)))} value={product.name} />
</div>
<div className="col-sm-6">
<label for="firstName" className="form-label">Цена</label>
<input type="text" className="form-control" id="productCost" required
onChange={(e) => setProduct((prevState => (
{
...prevState, cost: e.target.value
}
)))} value={product.cost}/>
</div>
</div>
<div className="row mt-3">
<div className="d-grid col-sm-4 mx-auto">
<button type="submit" className="btn btn-success">Добавить</button>
</div>
<div className="d-grid col-sm-4 mx-auto mt-3 mt-sm-0">
<button type="reset" className="btn btn-danger">Очистить инпуты</button>
</div>
<div className="d-grid col-sm-4 mx-auto mt-3 mt-sm-0">
<button id="testNormal" type="button" className="btn btn-secondary">Test</button>
</div>
</div>
</form>
<div className="row table-responsive">
<table className="table mt-3">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Наименование</th>
<th scope="col">Цена</th>
<th scope="col">Действие</th>
</tr>
</thead>
<tbody id="tbody">
{products.map((product, index) =>
<tr>
<td>{index + 1}</td>
<td>{product.name}</td>
<td>{product.cost}</td>
</tr>
)}
</tbody>
</table>
</div>
</div>
)
}