Reputation: 13
I am new to firebase and using ReactJs, I am wondering how can I update a specific data in Realtime database, I want to change the value of it to true or false interchangeably.
This is my code.
const [status, setStatus] = useState(false);
const [tempId, setTempId] = useState("");
const [todo, setTodo] = useState("");
const updateStatus = () => {
update(ref(db, `/${auth.currentUser.uid}/${tempId}`), {
completed: setStatus(!status),
todo: todo,
id: tempId,
});
};
Thank you in Advance.
Upvotes: 1
Views: 2549
Reputation: 598857
If you only want to update the status property, you can do:
update(ref(db, `/${auth.currentUser.uid}/${tempId}`), {
completed: !status
});
Since your calling update
, it will leave the other properties of the node unmodified.
Alternatively, you can do:
update(ref(db, `/${auth.currentUser.uid}/${tempId}/status`), !status)
Or:
set(ref(db, `/${auth.currentUser.uid}/${tempId}/status`), !status)
Both of these write to the complete path of just the status
property.
What you'll note is that I don't call setStatus
in the code above. Instead I recommend listening to the value of the status node, and then calling setStatus
when you get a callback there:
onValue(ref(db, `/${auth.currentUser.uid}/${tempId}/status`), (snapshot) => {
setStatus(snapshot.val());
});
Separating the read and write operations like this is known as command query responsibility segregation (or CQRS) and in the case of Firebase won't even be slower for the user, as the local SDK will immediately call the onValue
handler when you call set
or update
on that path.
Upvotes: 1