Issue
Updating data requires me to enter each individual piece of data in my Firestore document.
Editing the tag number will result in the contract number being overwritten with an empty string, and vice versa.
This is likely caused by the data being displayed as a placeholder. If I were to display data as a value, I am unable to make any changes whatsoever.
This is how data is displayed and entered (Ionic):
<IonItem>
<IonLabel>Contract No.:</IonLabel>
<IonInput placeholder={dataList?.contractNo} value={contractNo} onIonChange={(e) => setContractNo(e.target.value)}></IonInput>
</IonItem>
<IonItem>
<IonLabel>Tag No.:</IonLabel>
<IonInput placeholder={dataList?.tagNo} value={tagNo} onIonChange={(e) => setTagNo(e.target.value)}></IonInput>
</IonItem>
Get Data function:
function getData() {
setBusy(true);
const dataRef = firebase.firestore().collection("Data").doc(id);
dataRef.get(id).then(doc => {
const data = { id: doc.id, ...doc.data() }
setDataList(data);
});
setBusy(false);
}
The use-effect:
useEffect(() => {
getData();
}, []);
Update Data Function:
function updateData(updatedData) {
setBusy(true);
ref
.doc(updatedData.id)
.update(updatedData)
.catch((err) => {
console.error(err);
});
setBusy(false);
}
Update Button:
<IonButton onClick={() => updateData({
siteName: siteName, category: category, contractNo: contractNo, tagNo: tagNo, id: id
})}>Update<PencilSquare size={25}></PencilSquare></IonButton>
Const's:
const { id } = useParams();
const [dataList, setDataList] = useState([]);
const ref = firebase.firestore().collection("Data");
const [busy, setBusy] = useState(false);
const [contractNo, setContractNo] = useState("");
const [tagNo, setTagNo] = useState("");
Solution
When you pass a field to Firestore's update()
function, it assumes you want to set the field in the document to the value you specified. If you specify an empty string for the value, the field will be set to an empty string in the database too.
To not change the value of the field, you shouldn't pass that field in when calling update()
. So a simple fix would be to remove fields with empty strings as values in your updateData()
function:
function updateData(updatedData) {
setBusy(true);
let updatedFields = {};
Object.keys(updatedData).forEach((field) => {
if (updatedData[field] && updatedData[field].length > 0) {
updatedFields[field] = updatedData[field];
}
});
ref
.doc(updatedData.id)
.update(updatedFields)
.then(() => setBusy(false))
.catch((err) => {
console.error(err);
setBusy(false);
});
}
updatedData
Answered By - Frank van Puffelen
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.