import React, { useState, useEffect } from 'react';
import axios from 'axios';
const YourComponent = () => {
const [data, setData] = useState([]);
const [newProduct, setNewProduct] = useState({
name: '',
price: 0,
});
useEffect(() => {
fetchData();
}, []);
const fetchData = () => {
axios.get('http://localhost:5000/api/products')
.then((res) => {
setData(res.data);
})
.catch((error) => {
console.error('Error fetching data:', error);
});
};
const handleCreate = () => {
axios.post('http://localhost:5000/api/products', newProduct)
.then((res) => {
setData([...data, res.data]);
setNewProduct({
name: '',
price: 0,
});
})
.catch((error) => {
console.error('Error creating product:', error);
});
};
const handleUpdate = (productId, updatedProduct) => {
axios.put(`http://localhost:5000/api/products/${productId}`, updatedProduct)
.then((res) => {
const updatedData = data.map(product => (product.id === productId ? res.data : product));
setData(updatedData);
})
.catch((error) => {
console.error('Error updating product:', error);
});
};
const handleDelete = (productId) => {
axios.delete(`http://localhost:5000/api/products/${productId}`)
.then(() => {
const updatedData = data.filter(product => product.id !== productId);
setData(updatedData);
})
.catch((error) => {
console.error('Error deleting product:', error);
});
};
return (
{/* Render your component with data and CRUD operations */}
);
};
export default YourComponent;
Top comments (0)