Reputation: 1636
I'm developing an App using React Native and Firebase Real-Time Database.
In the database, I have some data as below.
myRoot
|
|--myValue1: 0
|
|--myValue2: 2
Then, I want to increase those values by one and get the following result.
myRoot
|
|--myValue1: 1
|
|--myValue2: 3
For this, I used a function as follows.
myFunction = () => {
const myRef = firebase.database().ref('myRoot');
return myRef.transaction((data) => {
data.myValue1++;
data.myValue2++;
return data;
})
.then(console.log('Done'))
.catch((error) => console.log(error));
}
But, after calling the function, I get the following error.
[Unhandled promise rejection: TypeError: null is not an object (evaluating 'data.myValue1')]
I tried taking a snapshot
of myRef
and print it in the console. It worked and printed the current values. But, transaction
does not work and gives null
.
Please help me to solve this problem.
Upvotes: 1
Views: 1015
Reputation: 1636
Found what caused the problem. The code segment is fine. The problem was in the dependencies. Just execute npm install firebase --save
and then npm install
. Restart the project. It worked!
Upvotes: 1
Reputation: 214
Something like this I believe Sennen:
myFunction = () => {
const myRef = firebase.database().ref('myRoot');
myRef.transaction((data) => {
if(data) {
if(data.myValue1) {
data.myValue1++;
}
if(data.myValue2) {
data.myValue2++;
}
}
return data;
})
.then(console.log('Done'))
.catch((error) => console.log(error));
}
Upvotes: 1
Reputation: 317477
You'll need to check data
for null, as this happens the first time the transaction handler function is called. The handler will get called again with the snapshot, if it's present at the location of the database where you are performing the transaction. You can see this check being performed in the sample code in the documentation.
Upvotes: 1