I am using .onUpdate function with snap.before.data() and snap.after.data() with a map field value. The issue is that the changes trigger doesn't seem to be working. It's calling both strat and mark functions, when only one map object (mark) has been updated.
I know that .onUpdate does not trigger with a fieldvalue, but .before and .after changes of a field value can be compared. Can this work with a parent map/object? Both mark and strat maps have no parents in the doc.
export const BARupdate = functions.firestore
.document('inputs/{inputUserID}')
.onUpdate(async (snap, context) => {
functions.logger.log('bar update is running');
// .after should represent after changes
const userInfo: any = {
...snap.after.data(),
userID: snap.after.id,
};
const newValue = snap.after.data();
const oldValue = snap.before.data()
if (userInfo['strat'] !== undefined) {
if (newValue.strat !== oldValue.strat){
console.log('snap same strat? NO')
const stratData = userBusinessInfo['strat'];
const userID = userBusinessInfo?.userID;
} else {
console.log('STRAT IS THE SAME')
}
return
}
if (userBusinessInfo['mark'] !== undefined) {
if (newValue.mark !== oldValue?.mark){
console.log('snap same mark? NO')
const markData = userInfo['mark'];
const userID = userInfo?.userID;
} else {
console.log('MARK IS THE SAME')
}
return
}
CodePudding user response:
The reason is that the map objects may be returned with their properties in a different order.
Since you only have two properties by object, you can modify your code as follows:
if (newValue.strat.id !== oldValue.strat.id || newValue.strat.name !== oldValue.strat.name) {
console.log('snap same strat? NO')
//...
} else {
console.log('STRAT IS THE SAME')
}
if (newValue.mark.id !== oldValue.mark.id || newValue.mark.name !== oldValue.mark.name) {
console.log('snap same mark? NO')
//...
} else {
console.log('MARK IS THE SAME')
}
In case the map objects are more complex, you should use another approach, e.g. using the lodash library, which performs a deep comparison between two values to check if they are equivalent with _.isEqual(value1, value2)
.
See also: https://www.google.com/search?q=javascript how to compare two objects