Reputation: 1765
hello im trying to update document in firestore with cloud functions but im confused on how cloud functions know which document to update here is my code
cloud functions code
exports.newsletterGreetConfirm = functions.firestore
.document('newsletter/{newsletterId}')
.onUpdate((change, context) => {
const newValue = change.after.data();
console.log(newValue);
return 0;
});
in my cloud functions shell ill pass the following object to my newsletterGreetConfirm
function
{email:"[email protected]",id:"LgNqtD6Ih7SYPEEz8jJl",subscribedToNewsletterList:true,timestamp:12321312}
my output is undefined
my goal is to confirm email addresses whenever a user clicks a button or link in their confirmation email. just in the first phase of building this functionality thanks for all the help! also im using react
Upvotes: 7
Views: 12661
Reputation: 2885
The idea is to either generate an HTTP request directly to firebase via a URL sent in the email, or to do it through React.
You could send them to the URL example.com/verify/USER_DOC_ID
Assuming you use react-router-dom
, and you want to use the web firebase API to avoid creating an HTTP request, you would do something like the following in your React component (this also assumes you are using firestore in React correctly):
import React, {Component} from 'react':
import firestore from './firestore'; //this is your config file
import {withRouter} from 'react-router-dom';
class Verify extends Component {
componentDidMount(){
const {pathname} = this.props.location;
const ID = pathname.split('/')[2];
//DO THE FIREBASE UPDATE HERE
}
render(){...}
export default withRouter(Verify);
Now, you have a few options for where I placed //DO THE FIREBASE UPDATE HERE
. You can either create an http request to firebase, or you can use web side firebase. If you're using web side firebase, you would just update the document in firebase (note that you wouldn't need to import firestore in react if you are doing a fetch request.)
the react way involves something like this:
const ref = firebase.firestore().collection('newsletter').doc(ID);
ref.get().then((doc) => {
if(doc.exists()){
ref.update({verified: true});
});
The logic for interacting with firestore is very similar on the backend with the Admin API, however you'll wrap it in an HTTP request in cloud-functions:
exports.verify = functions.https.onRequest((req, res) => {
// admin api call with req params or body
});
With the above code you can either navigate directly here from the email, responding with HTML directly, or you can call it via a fetch request in the react app like fetch("https://example.com/verify/ID").then(...)
.
If you want more details about any one of the above methods I described, post it as a separate question if you can't find it on SO, let me know, and I'll do my best to answer.
Upvotes: 6