I'm trying to get data from firebase. I receive the data as an Object and it shows the data I want. However when I try to get a specific value from an Object property it says it's undefined. What am I doing wrong or what am I missing?
export const createChat = () => {
return async dispatch => {
dispatch({ type: CREATE_SINGLE_CHAT });
const creator = firebase.auth().currentUser.uid;
const userRef = firebase.database().ref(`/users/${creator}`);
const currUser = await userRef.once('value');
console.log(currUser);
console.log(currUser.name);
};
};
Here is the console.log:
23:30:58 // currUser
Object {
"email": "a#b.de",
"is24Hours": true,
"name": "Alex",
}
23:30:58 // currUser.name
undefined
I'm using React Native with Redux and Redux-Thunk and also the realtime-database from firebase as database.
As Max Brodin mentioned I forgot to use the val() method from firebase:
firebase.google.com/docs/database/web/read-and-write
working code:
export const createChat = () => {
return async dispatch => {
dispatch({ type: CREATE_SINGLE_CHAT });
const creator = firebase.auth().currentUser.uid;
const userRef = firebase.database().ref(`/users/${creator}`);
const currUser = await userRef.once('value');
console.log(currUser);
console.log(currUser.val().name); // here is the change
};
};
Related
I am trying to use getInitialProps to get items from a firebase database, but to do so, I need the current user Id. However when i pass the user id object as a context to getInitialProps, it is null. Please help.
inside the main dashboard method, I have access to auth.currentUser.uid, but it appears null when I try to use it in get initial props
Dashboard.getInitialProps = async (context) => {
console.log(auth?.currentUser?.uid);
console.log("is this working");
const userRef = ref(database, "users/" + auth?.currentUser?.uid);
const getUser = async () => (await get(userRef)).val();
const data = await getUser();
const userInfo = await data;
console.log(userInfo);
if (!userInfo) return { notFound: true };
return {
props: userInfo,
};
};
I have the following node:
attendanceOptions: {
uid1: 'blah#example.com',
uid2: 'tap#example.com'
}
I'm trying to return only the key and value where value is equal to. These are my two attempts.
const getMinistry = await admin.database().ref(`organization/${req.orgId}/attendanceOptions`)
getMinistry
.equalTo(req.memberUid)
.once('value', snapshot => {
functions.logger.log(snapshot.val())
});
This returns null
I also tried:
const getMinistry = await admin.database().ref(`organization/${req.orgId}`)
getMinistry
.orderByChild('attendanceOptions')
.equalTo(req.memberUid)
.once('value', snapshot => {
const data = snapshot.val();
functions.logger.log( `this is data: ${data}` )
return data;
});
The log is this is data: null
In my rules I have:
"attendanceOptions": {
".indexOn": [".value"]
},
What am I doing wrong here?
The correct syntax is:
getMinistry
.child('attendanceOptions')
.orderByValue()
.equalTo(req.memberUid)
I am writing a test which tests a firebase trigger. The problem, however, is that I cannot make it work.
I want to use the local firestore emulator and Jest in order to simulate a change in the firestore and see if the trigger does what it needs to do.
I require the cloud function in my test and I initialize my app
Setup.js:
const firebase = require('#firebase/testing');
const PROJECT_ID = 'project';
let admin;
let db;
const setupAdmin = async () => {
admin = firebase.initializeAdminApp({
projectId: PROJECT_ID
});
db = admin.firestore();
};
const getAdmin = () => {
return admin;
};
const getDb = () => {
return db;
};
module.exports.setupAdmin = setupAdmin;
module.exports.getAdmin = getAdmin;
module.exports.getDb = getDb;
Test.js
describe('Billing', () => {
let dbRef;
beforeAll(async () => {
const {db, admin} = require('../../../functions/helpers/setup');
dbRef = db;
});
afterAll(async () => {
await Promise.all(firebase.apps().map(app => app.delete()));
console.log(`View rule coverage information at ${COVERAGE_URL}\n`);
});
it('test', async () => {
const mockData = {
'Users/user1': {
uid: 'user1'
},
['Users/user1/Taxes/' + new Date().getFullYear().toString()]: {
totalExpenseEuro: 0
}
};
for (const key in mockData) {
const ref = dbRef.doc(key);
await ref.set(mockData[key]);
}
// Create mockup data
await dbRef.collection('Users').doc('user1').collection('Expenses').doc('expense1').set({
amountEuroInclVAT: 100
});
// Make snapshot for state of database beforehand
const beforeSnap = test.firestore.makeDocumentSnapshot({amountEuroInclVAT: 0}, 'Users/user1/Expenses/expense1');
// Make snapshot for state of database after the change
const afterSnap = test.firestore.makeDocumentSnapshot(
{amountEuroInclVAT: 100},
'Users/user1/Expenses/expense1'
);
const change = test.makeChange(beforeSnap, afterSnap);
// Call wrapped function with the Change object
const wrapped = test.wrap(calculateTaxesOnExpenseUpdate);
wrapped(change, {
params: {
uid: 'test1'
}
});
});
});
Now the main problem comes when I try to access this db object in my trigger
const calculateTaxesOnExpenseUpdate = functions.firestore
.document('Users/{uid}/Expenses/{expenseId}')
.onWrite(async (change, context) => {
const {getDb} = require('../helpers/setup'); // This setup is the same as above
let db = getDb();
...
For some reason when I perform an action like (await db.collection('Users').get()).get('totalExpenseEuro'), Jest stops executing my code. When I set a debugger right after that line, it never gets printed. That piece of code crashes, and I have no idea why. I think the DB instance if not properly configured in my cloud trigger function.
Question: What is a good way of sharing the DB instance (admin.firestore()) between the test and the cloud trigger functions?
I'm trying to fetch a value from my firebase DB and I'm using the following code:
export const getCode = async key => {
let ref = await database.ref ('games/' + key).once('value');
console.log(ref);
console.log(ref.code);
return ref;
};
The results I get from each console.log are these:
the ref returns
Object {
"code": 665195,
"users": Object {
"-MA5m0PrOWUuz-KdcmRx": Object {
"username": "לעג",
},
},
}
but ref.code returns undefined
screenshot
I've spent hours on my code and stackoverflow and couldn't find an answer. Hopefully you could.
you didn't use ref.val() to get values.
try
export const getCode = async key => {
let ref = await database.ref('games/' + key).once('value');
const data = ref.val();
console.log(data);
console.log(data.code);
return data.code;
};
If ref gets logged as the following:
Object {
"code": 665195,
"users": Object {
"-MA5m0PrOWUuz-KdcmRx": Object {
"username": "לעג",
},
},
}
I suspect that it could be that you're getting a json string as a response, unless your development environment quotes keys by default.
Maybe try let ref = JSON.parse(await database.ref ('games/' + key).once('value'));
Shouldn't the ref variable be returned? You haven't declared anything named code hence why it's undefined.
export const getCode = async key => {
let ref = await database.ref ('games/' + key).once('value');
return ref.code;
};
You could also do like the cool kids and make this single line if you are gonna use it as it is.
export const getCode = async key => await database.ref ('games/' + key).once('value').code
I am trying to extract value in React hooks but in meantime when I console customer I got this error TypeError: Cannot read property 'firstName' of null I don't know what issue have in my code . I am new to React Hook could someone please help me how to solve this problem .
Thanks
When I console Customer , I am getting this result
Result View
When I console customer.firstName
It give me error
Code
const [customer, setCustomer] = useState(null);
async function fetchMyAPI() {
let response = await fetch(
`/api/requirements/find?customerId=${item.customerId}`
);
response = await response.json();
console.log(response);
setCustomer(response);
}
useEffect(async () => {
fetchMyAPI();
}, []);
In return function
{console.log(customer.firstName)}
The error makes sense, you are using Object notation to reach the value belonging to something that is not an object.
Just set your initial-state as an empty object to resolve your console error:
const [customer, setCustomer] = useState({});
Overall code:
const Customer = () => {
const [customer, setCustomer] = useState(null);
async function fetchMyAPI() {
let response = await fetch(
`/api/requirements/find?customerId=${item.customerId}`
);
let data = await response.json();
console.log(data);
setCustomer(data);
}
useEffect(async () => {
fetchMyAPI();
}, []);
return(
<div>
<h4>{customer.firstName}</h4>
<h4>{customer.lastName}</h4>
</div>
)
}
You can set the initial state as blank object like below...
const [customer, setCustomer] = useState({});
OR
You may set the default structure of object like below...
const [customer, setCustomer] = useState({firstName: '', lastName: ''});