In my react/nextjs app, I am trying to update a field in the 'users' collection in my firestore db using a form.
WriteOrgToCloudFirestore
import { db } from "@/lib/firebase/initFirebase";
import { doc, updateDoc, setDoc } from "firebase/firestore";
import { useUser } from "@/lib/firebase/useUser";
import { useState } from "react";
const WriteOrgToCloudFirestore = () => {
const { user } = useUser();
const [orgName, setOrgName] = useState("");
const handleChange = (event) => {
setOrgName(event.target.value);
};
const sendData = async () => {
try {
const userDoc = doc(db, "users", user.id);
console.log('db',db);
await setDoc(userDoc, {
orgName: orgName,
});
alert("User Data was successfully sent to cloud firestore!");
} catch (error) {
console.log(error);
alert(error);
}
};
return (
<div style={{ margin: "5px 0" }}>
<form onSubmit={sendData}>
<input type="text" value={orgName} onChange={handleChange} />
<input type="submit" style={{ width: "100%" }} value="send message" />
</form>
</div>
);
};
export default WriteOrgToCloudFirestore;
When I send the data, I am not getting an error message. However, no data is being written to the DB.
I have another write file which is almost the same but with prefilled data. If I manually update it with new string values, I see the updates in the "myCollections" collection in the firebase console:
import { db } from '@/lib/firebase/initFirebase'
import { doc, setDoc, Timestamp, GeoPoint } from "firebase/firestore"
import { useUser } from '@/lib/firebase/useUser'
import Button from 'react-bootstrap/Button'
const WriteToCloudFirestore = () => {
const { user } = useUser()
const sendData = async () => {
try {
const userDoc = doc(db, "myCollection", user.id)
await updateDoc(userDoc, {
string_data: 'Benjamin Carlson',
number_data: 2,
boolean_data: true,
map_data: { stringInMap: 'Hi', numberInMap: 7 },
array_data: ['text', 4],
null_data: null,
time_stamp: Timestamp.fromDate(new Date('December 17, 1995 03:24:00')),
geo_point: new GeoPoint(34.714322, -131.468435)
})
alert('Data was successfully sent to cloud firestore!')
} catch (error) {
console.log(error)
alert(error)
}
}
return (
<div style={{ margin: '5px 0' }}>
<Button onClick={sendData} style={{ width: '100%' }}>Send Data To Cloud Firestore</Button>
</div>
)
}
export default WriteToCloudFirestore
When submitted, the alert is shown with the success message.
Though the files are nearly identical, I'm not sure why I am not able to see my submission in the WriteOrgToCloudFirestore.js file.