I wanted to decrement the quantities of the color
upon submitting the form. So, I have these forms where the user can choose a product and also enter the quantity and choose a color(s). And then also allows the user to add more products and so on.
This is what the data looks like if I'll submit it:
And these are the firestore documents for the Shirt
and Notebook
How can I create a function to decrement the specific values that were in the data above upon submitting? I only tried hardcoding the document ID and then decrement it, and it does work. However, I am unsure of how to do this dynamically.
I've assumed that the qty
is equal to 10 just to see if it really does decrement. And it does. Also, I'm not using any admin SDK.
const qty = 10;
async function updateData(color) {
const docRef = doc(db, "products", "m08YmrlFxhxLxyc3hVjT");
await updateDoc(docRef, {
[`colorMap.Black`]: increment(`${-qty}`),
[`colorMap.Gold`]: increment(`${-qty}`),
});
const docRef2 = doc(db, "products", "nN2w57SiDovbtQ6EBzGb");
await updateDoc(docRef2, {
[`colorMap.green`]: increment(`${-qty}`),
[`colorMap.red`]: increment(`${-qty}`),
});
}
This is my form:
index.js Where I submit it:
import React from "react";
import { useForm } from "react-hook-form";
import FieldArray from "./fieldArray";
import ReactDOM from "react-dom";
import "./styles.css";
import { Button } from "@mui/material";
const defaultValues = {
test: [
{
product: "",
nestedArray: [{ size: "", color: "", design: "" }]
}
]
};
function App() {
const {
control,
register,
handleSubmit,
getValues,
errors,
reset,
setValue
} = useForm({
defaultValues
});
const onSubmit = (data) => {
console.log(data);
try {
//codes here to submit the data in the another collection
//then a function to decrement the values.
} catch (err) {
console.log(err);
}
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<h1>Array of Array Fields</h1>
<p>
The following example demonstrate the ability of building nested array
fields.
</p>
<FieldArray
{...{ control, register, defaultValues, getValues, setValue, errors }}
/>
<button type="button" onClick={() => reset(defaultValues)}>
Reset
</button>
<Button type="submit">Submit</Button>
{/* <input type="submit" /> */}
</form>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
CodePudding user response:
Not sure if it is the cause of the problem, but this seems wrong:
increment(`${-qty}`)
Firestore's increment
function takes a numerical value, and you are passing a string. The proper invocation is:
increment(-1 * qty)