Firebase get user data during onCreate - firebase

After an user creation, I have difficult to retrived data in a onCreate method.
exports.accountCreate = functions.auth.user().onCreate(user => {
console.log("--->"+user.data);
console.log("ok");
return true;
});
But I received an undefined value

As you can see in the API documentation, the onCreate callback method receives a UserRecord object as its first argument. Your function is calling it user, and is trying to access a property called data on it. But you can see that UserRecord doesn't have a data property. It has lots of other properties, so try one of them instead. Or maybe call its toJSON method to generate an object that you could also log.

Related

SvelteKit load function error: must return a plain object at the top level

I cannot get SvelteKit load function works when using it with Firebase, I always get this error message:
a load function related to route '/' returned a function, but must return a plain object at the top level (i.e. return {...})
I'm using onSnapshot here with Firestone to get the updated data whenever it changed on the database.
export function load() {
const queryParams = [orderBy('date')];
const q = query(collection(db, 'daily_status'), ...queryParams);
messagesUnsubscribeCallback = onSnapshot(
q,
querySnapshot => {
let data = querySnapshot.docs.map( doc => (
JSON.parse(JSON.stringify(
{
id: doc.id,
status: doc.data().status,
date: doc.data().date.toDate().toLocaleDateString('en-au'),
note: doc.data().note
}
))
))
return { daily_status: data }
})
return messagesUnsubscribeCallback;
}
It looks like your issue is the fact that you are returning the function onSnapshot() inside the load function. The only thing you can return inside a load method is a plain object as the error states. What you might want to do is to run the snapshot code inside an onMount.
Another solution would be creating a svelte store and pass the onSnapshot into the store. An example can be seen in this tutorial:
https://www.captaincodeman.com/lazy-loading-and-querying-firestore-with-sveltekit#introduction
Reference:
https://kit.svelte.dev/docs/load
Your load() function needs to run asynchronous code, so it can't return back the data directly. Instead, you need to change it to return a promise that resolves to the loaded data. For an example using fetch(), see:
https://kit.svelte.dev/docs/load#making-fetch-requests
In your case, you need to create your own promise.
Further more, the purpose of the load() function is to load the initial data the page needs to be able to render. As suggested by another, to subscribe to updates in the future, do that in the page component in onMount(), so you only subscribe to future updates when the component is rendered in the web browser.

Firebase await error: Some requested document was not found

async function confirmCode() {
try {
data = await confirm.confirm(code);
if(data.additionalUserInfo.isNewUser){
await firestore.collection("Users").doc(auth.currentUser.uid).update({
id:auth.currentUser.uid,
})
}
} catch (error) {
console.log(error)
}
//Error: [firestore/not-found] Some requested document was not found.
When I use this code to create user & also make firestore data of user it returns error.
But if user is already created, this returns wonderful result.
Any helps can I get to successfully create firestore data when new user comes?
From the error message //Error: [firestore/not-found] Some requested document was not found. is seems that you have a problem with the Firestore document you try to update with await firestore.collection("Users").doc(auth.currentUser.uid).update();
One classical problem when using auth.currentUser is that it is possible that the Auth object is not fully initialized and that auth.currentUser.uid is therefore null. As explained in the doc you should either use the onAuthStateChanged() observer or check that auth.currentUser is not null.
It may also happen that the document is not existing for another reason (e.g. you never created it!): since you are calling update() the document must exist, see the doc: "The update will fail if applied to a document that does not exist.".

(React native) Can't get data out of the Firebase database method

i trying to get the data from my database, in componentWillMount(), it works fine with this :
var userData = null
firebase.database().ref('/users/' + user.uid).once('value').then(function(snapshot) {
userData = snapshot.val()
console.log(userData)
});
But it only works in the method only, i tried to asign the value to a variable but i can't get it outside even with this.setstate.
I am really lost it looks easy but i don't know how ...
Thanks for help.
once() is asynchronous and returns immediately with a promise. The promise does not block your code when you attach a then callback to it. userData won't be populated in the callback from the promise until after the database query completes, and you have no guarantee when that will be. If your code tries to access userData before it's finally populated, it will still have its original null value.
Well, what's happening here is,
your firebase method is taking a time to get data and because everything is asynchronous here, javascript will not wait until your firebase method is executed.
Immediate next line of firebase.database().... will be executed before this completes.
So you might need to set your data into state using setState or you can use a class variable instead of a local variable.
do this,
constructor(props){
super(props);
this.state={
data:null //either do this
}
this.localData=null; // or this
}
firebase.database().ref('/users/' + user.uid).once('value').then(function(snapshot) {
this.setState({data:snapshot.val()});
this.localData = snapshot.val();
console.log(this.localData)
});

Firestore Cloud Function - Get request data object in onUpdate/onCreate

When writing firebase rules, you can access the request data via request.resource.data. This is useful because you can look at the nature of the request to determine its intent, its write target and permit or deny. This enables merging properties into an object within a document owned by a user, vs using a nested collection of documents.
I would like to access the same request data in the cloud function callbacks update/write/etc, but I don't see it, and I'm left to do an object compare with change.before and change.after. It's not a problem, but did I miss something in the documentation?
Per documentation: https://firebase.google.com/docs/firestore/extend-with-functions
exports.myFunctionName = functions.firestore.document('users/marie').onWrite((change, context) => {
// ... the change or context objects do not contain the request data
});
I had the exact same question when I realized that a function listening for updates was being triggered regardless of the property being updated, despite having a 'status' in data check. The catch that data represented handler.after.data. Although I wasn't able to access the request data, either from the handler or from the context, I was able to solve the problem by adding an additional check which serves the same purpose. Namely:
const dataBefore = handler.before.data();
const dataAfter = handler.after.data();
if (status in dataBefore && status in dataAfter) {
if (dataBefore.status === 'unpublished' && dataAfter.status === 'published') {
// handle update
}
}

How get autoID of new object after calling push() in firebase?

It's simple. I have an object called obj and the reference called ref
when I do:
ref.push(obj, function(err){});
or
ref.push().set(obj, function(err){});
how do I get the auto generated ID of the recently saved object?
The push function returns a reference to the newly created object.
var newRef = ref.push();
console.log(newRef.name());
newRef.set(obj, function(err) {});
Note that in the above snippet no data is sent to the server until the call to set. The push() method is pure client-side, as long as you don't pass any data into it.
https://www.firebase.com/docs/web/api/firebase/push.html

Resources