Problem Definition
I am having React App with small shop where all products are coming just from JSON file as external API since I am handling everything on fronten.
But I just got in one product that has limited amount -> I have only 20psc of that product and I am not sure how I can limit the users to purchasing more than I actually have.
Questions
Is that somehow possible with still using just API or do I have to revert everything into DB (firebase for example)?
Any suggestions and example links I appriciate!
This is how I currently handle it with unlimited amount of products
// fetch data here
const fetchData = () => {
fetch('myAPIendpoint')
.then((response) => response.json())
.then((data) => {
setProducts(data);
})
.catch((error) => {
console.log(error);
});
};
React.useEffect(() => {
fetchData();
}, []);
// adding product to cart
const onAdd = (product) => {
const exist = cartItems.find((x) => x.id === product.id);
if (exist) {
setCartItems(
cartItems.map((x) =>
x.id === product.id ? { ...exist, qty: exist.qty + 1 } : x
)
);
} else {
setCartItems([...cartItems, { ...product, qty: 1 }]);
}
};
// mapping items to show it in cart
{cartItems.map((item) => (
.....
.....
You can just rewrite amount of product left dirrectly in your JSON file.
ex. Somebody buying some product -> request sent to your API -> you are reading the JSON file, looking for product by id(.find(product => producct.id === id)). Then you are checking quantity of product (do you have needed amount or not) if not, then returning some error, if yes, then you are doing rewrite of quantity property of the product inside file for current product and do other business logic.
Work with files depends on techonlogy/programmming language you use on back-end side. You can find it separately.