Reputation: 65
I am trying to write to Firebase DB in a React application. It adds new data entry if I use DB reference and set method. However, it writes a whole new data when I use the same method through redux action.
This is the code that works.
const notesRef = firebase.database().ref('notes');
const noteRef = notesRef.child(this.state.noteId);
const note = {
text: this.state.text,
timestamp: this.state.timestamp,
title: this.titleTextArea.value,
}
noteRef.set(note);
This is the action
export const addNote = (newNoteId, newNote) => async dispatch => {
notesRef.child(newNoteId).set(newNote);
};
const note = {
text: this.state.text,
timestamp: this.state.timestamp,
title: this.titleTextArea.value,
}
this.props.addNote(this.state.noteId, note);
Bad result:
notes: "a6ff48e4-f34a-483f-a639-b0dbfd703009"
Good result:
notes:
b85def67-3877-4d2f-b5c7-23d8295768ad
text: "{\"ops\":[{\"insert\":\"fsasfs\\n\"}]}"
timestamp: 1557467143056
title: "asfa"
e4290153-a40c-464f-a92a-39eded74bd2a
text: "{\"ops\":[{\"insert\":\"sadfasdfsd\\n\"}]}"
timestamp: 1557467154054
title: "asdfsdaf"
Upvotes: 0
Views: 103
Reputation: 681
Basic rule is Set overrides and Update is specific to each node. Use update instead. You can also use push to have firebase automatically generate a unique node name:
Set:
Using set() overwrites data at the specified location, including any child nodes.
Update:
To simultaneously write to specific children of a node without overwriting other child nodes, use the update() method.
https://firebase.google.com/docs/database/web/read-and-write https://firebase.google.com/docs/database/admin/save-data
Upvotes: 1
Reputation: 3384
So what 'set' function of firebase does it replace existing data with the new one. Use 'update' function to update db.
//get new key
var newPostKey = firebase.database().ref().child(newNoteId).push().key;
//Update existing
export const addNote = (newNoteId, newNote) => async dispatch => {
let update = {}
update[newPostKey] = newNote
notesRef.update(update);
};
Happy Coding :)
Upvotes: 1