Reputation: 1829
I have these textfields to update an item. How can I set an initial value for the productName and productPrice?
I already have these productName and productPrice data which was taken from a row in the previous page and was stored in this edit form in a location.state
.
I already have these data stored in the location.state
:
Currently, if I am going to update the data and will only enter a value in the product price field, the product name field would be saved as an empty string in the firestore. I wanted to set an initial value for each of the textfield with their corresponding data so that even if the user will only update the product price field, the productName will be saved as it is "Item1" and won't be save as an empty string. I tried having a defaultValue and it does not work.
const edit = () => {
const location = useLocation();
const data = location.state;
const [Product, setProduct] = useState([]);
const [productName, setProductName] = useState("");
const [productPrice, setProductPrice] = useState("");
useEffect(() => {
firestore
.collection("products")
.doc(data)
.onSnapshot((snapshot) => {
const arr = [];
arr.push({
...snapshot.data(),
});
setProduct(arr);
});
}, []);
const handleSubmit = async (event) => {
event.preventDefault();
try {
const Ref = firestore.collection("products").doc(data);
const res = Ref.set(
{
productName,
productPrice,
},
{ merge: true }
);
alert("Successfully updated");
} catch (err) {
console.log(err);
}
};
return (
<div>
{products.map((prod, index) => (
<div>
<form onSubmit={handleSubmit}>
<FormControl>
<TextField
id="input"
type=”text”
label="Product Name"
value={productName}
defaultValue={prod.productName)
onChange={(e) => setProductName(e.target.value)}
/>
<TextField
id="input"
margin="dense"
type="text"
label="Product Price"
value={productPrice}
defaultValue={prod.productPrice)
onChange={(e) => setProductPrice(e.target.value)}
/>
<Button
type="submit"
>
Update
</Button>
</FormControl>
</form>
</div>
))}
</div>
);
};
export default edit;
Upvotes: 0
Views: 125
Reputation: 111
Since it is provided that the variable named data has the default product details
The state could be initialized in this way
const [productName, setProductName] = useState(data.productName);
const [productPrice, setProductPrice] = useState(data.productPrice);
So these default values will be picked up by the text fields
Upvotes: 1
Reputation: 2947
I already have these data stored in the location.state:
- productName - Item1
- Blockquote
productPrice - 2.00
What about this?
const location = useLocation();
const [productName, setProductName] = useState(location.state.productName);
const [productPrice, setProductPrice] = useState(location.state.productPrice);
Upvotes: 1
Reputation: 633
In the onChange prop, try to check if e.target.value is not empty, else assign the old or the default product name.
onChange={(e) => setProductName(e.target.value ? e.target.value : prod.productName)}
Upvotes: 0