user15314274
user15314274

Reputation: 13

Update only specific data in Realtime database of Firebase v9

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.

Image

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

Answers (1)

Frank van Puffelen
Frank van Puffelen

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

Related Questions