I require some help that I couldn't find easily in the documentation.
So I've gotten my head around how to create a document in firebase on signup and setting the doc's ID to the current users uid. Now I want to reference the current user's doc and use its data throughout screens.
This is the function I use to retrieve the data:
const user = auth.currentUser;
const GettingUserData = async() => {
const userData = firestore.collection('users').doc(user.uid);
const doc = await userData.get();
if (!doc.exists) {
console.log('No such document!');
} else {
console.log('User data:', doc.data());
}
}
how would I go about using the data inside of doc.data() in something like <Text>{data.displayName}</Text>
Help or a link to read through would be greatly appreciated!
To manage remote data, you need a state to store that information.
If you are using a functional component:
const [userData, setUserData] = React.useState(null)
const user = auth.currentUser;
const GettingUserData = async() => {
const userData = firestore.collection('users').doc(user.uid);
const doc = await userData.get();
if (!doc.exists) {
console.log('No such document!');
} else {
console.log('User data:', doc.data());
setUserData(doc.data)
}
}
return (<View><Text>{userData?.name}</Text></View>)
if you are using class components:
const user = auth.currentUser;
const GettingUserData = async() => {
const userData = firestore.collection('users').doc(user.uid);
const doc = await userData.get();
if (!doc.exists) {
console.log('No such document!');
} else {
console.log('User data:', doc.data());
this.setState({userData: doc.data()})
}
}
return (<View><Text>{this.state.userData?.name}</Text></View>)
Related
This is my first time using Stripe in a project and I want to set up a subsciption system just to see if its possible. When I am trying to follow a tutorial for how to set it up, it always returns an error. Currently, I am at the part where I am trying to redirect the current user to the purchase page where they can sign up for the subscription, but I cannot seem to figure out a few key details. I am sharing the code for the checout session that I created.
import getStripe from "./initializeStripe";
import { db } from "../configs/firebase-config";
import { addDoc, collection, doc, onSnapshot } from "firebase/firestore";
export async function createCheckoutSession(uid) {
const location = "users/" + uid;
const docRef = collection(db, location, "checkout_sessions");
const checkoutSessionRef = await addDoc(docRef, {
price: "NEXT_PUBLIC_PRICE_KEY",
success_url: window.location.origin,
cancel_url: window.location.origin,
});
console.log();
onSnapshot(checkoutSessionRef, async (doc) => {
const { sessionId } = doc.data();
console.log(sessionId);
if (sessionId) {
const stripe = await getStripe();
stripe.redirectToCheckout({ sessionId });
}
}, [doc]);
}
Please let me know if you have any questions and I would be happy to provide with more code. I am working in NextJs 12 and Firebase Version 9
Edit: Let me add the initalizeStripe function too for more context.
import { Stripe, loadStripe } from "#stripe/stripe-js";
export const initializeStripe = async ({lineItems}) => {
let stripePromise = Stripe | null;
const getStripe = () => {
stripePromise = loadStripe(process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE);
return stripePromise;
};
// const stripe = await getStripe();
await stripe.redirectToCheckout({
mode: 'payment',
lineItems,
successUrl: `${window.location.origin}?session_id={CHECKOUT_SESSION_ID}`,
cancelUrl: window.location.origin,
})
return getStripe();
};
Traying to grab company ID stored in a user Object in firebase.
const handleSubmit = async (e) => {
e.preventDefault()
setError('')
try {
const { user } = await signIn(email, password)
const userID = await user.uid
const compID = doc(db, 'Users', user.uid)
console.log(userID + ' USERID')
console.log(compID.companyID + ' COMPANYID')
navigate('/Main/Dashboard')
} catch (e) {
setError(e.message)
console.log(e.message)
}
}
Tried logging it and I get undefined. If I put the whole path in the const compID then I get an invalid error due to having and odd number of selectors.
You need to actually fetch the document. What you have done now is create a query but not executing it.
To fetch the user document, do like this instead:
const { user } = await signIn(email, password)
const userID = user.uid
const docRef = doc(db, "Users", userID);
const docSnap = await getDoc(docRef);
if (docSnap.exists()) { // Check if the document exists before accessing data
const data = docSnap.data()
// Access compId by:
const compID = data.companyID
console.log("Here is you company id:", compID);
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
I am building an app with firebase .
I had successfully implemented a function that will enable the user to upload a pic to firebase storage
here it is
const uploadImageToBucket = async () => {
let blob;
try {
setUploading(true);
blob = await getPictureBlob(image);
const ref = await storage.ref().child(uuid.v4());
const snapshot = await ref.put(blob);
return await snapshot.ref.getDownloadURL();
} catch (e) {
alert(e.message);
} finally {
blob.close();
setUploading(false);
}
};
the problem is that I want the picture to be uploaded based on certain user and I want to set that pic as user profile pic .any suggestion please!!
here the user sign up function
const handleSignUp = () => {
setErrortext("");
if (!FullName) return alert("Please fill Name");
if (!Email) return alert("Please fill Email");
if (!Password) return alert("Please fill Address");
setIsLogged(true);
firebase
.auth()
.createUserWithEmailAndPassword(Email, Password)
.then((user) => {
alert("Registration Successful. Please Login to proceed");
console.log(user);
if (user) {
firebase
.auth()
.currentUser.updateProfile({
displayName: FullName,
})
.then(() => navigation.replace("Log_In"))
.then(() => {
firebase.auth().onAuthStateChanged((userData) => {
setuserData(userData);
});
})
.catch((error) => {
console.log(error);
setErrortext(error);
});
}
})
.catch((error) => {
if (error.code === "auth/email-already-in-use") {
setErrortext("That email address is already in use!");
setIsLogged(false);
} else {
setErrortext(error.message);
setIsLogged(false);
}
});
};
You can simply use updateProfile method to update currently logged in user's photoURL and set it to the download URL just requested. The uploadImageToBucket function returns that URL back so you can try this:
uploadImageToBucket().then(async (photoURL) => {
const user = firebase.auth().currentUser
await user.updateProfile({ photoURL })
console.log("Photo URL updated")
})
I started this tutorial (https://www.freecodecamp.org/news/react-native-firebase-tutorial/) on Firebase and React Native. Everything is working well overall.
But I have this error: “User does not exist anymore.” for the Login.
However, users are well rooted in Firebase.
const onLoginPress = () => {
firebase
.auth()
.signInWithEmailAndPassword(email, password)
.then((response) => {
const uid = response.user.uid
const usersRef = firebase.firestore().collection('users')
usersRef
.doc(uid)
.get()
.then(firestoreDocument => {
if (!firestoreDocument.exists) {
alert("User does not exist anymore.")
return;
}
const user = firestoreDocument.data()
navigation.navigate('Home', {user})
})
.catch(error => {
alert(error)
});
})
.catch(error => {
alert(error)
})
}
With
const usersRef = firebase.firestore().collection('users')
usersRef
.doc(uid)
.get()
.then(firestoreDocument => {
if (!firestoreDocument.exists) {
alert("User does not exist anymore.")
return;
}
const user = firestoreDocument.data()
navigation.navigate('Home', {user})
})
you actually query the user document with the id corresponding to the user's uid in the users collection.
This document is normally created by the onRegisterPress() function in the tutorial. If you get the "User does not exist anymore." message, it means that the user document is not present in the collection.
So you need to check why this is the case: the onRegisterPress() function was not called? The doc was deleted? There are security rules that prevent creating the document? etc...
I want to add a chat feature in my application, but the problem is while working with react-native-gifted-chat and firebase as a backend and its secured rules that gives an error of missing _id and user.
I tried using the firebase database and without using secured rules but the issue is it seems to be like a group chat rather than one to one (private) chat.
async UNSAFE_componentWillMount() {
const name = auth().currentUser.displayName;
const friendName = this.state.friendName;
this.setState({ name: name });
const ref = await database().ref(`chatmessages/`);
// Fetch the data snapshot
const snapshot = await ref.once('value');
console.log(snapshot, "Snapshot")
console.log(ref, "database");
}
componentDidMount() {
this.on(message => {
console.log(this.state.messages, 'old message')
this.setState(previousState => ({
messages: GiftedChat.append(previousState.messages, message),
})
)
});
}
componentWillUnmount() {
this.off();
}
get uid() {
return (auth().currentUser || {}).uid;
}
get ref() {
return database().ref(`chatmessages/`)
// .set();
}
parse = async snapshot => {
const data = snapshot.val();
const userID = auth().currentUser.uid;
const friendID = this.state.friendID;
const validate = data.friend === friendID && data.user._id === userID ||
data.user._id === friendID && data.friend === userID;
console.log(data.user, data.user._id, data.user.name, "MEssage Data")
if (validate) {
const { timestamp: numberStamp, text, user, friend } = await data;
const { key: _id } = snapshot;
console.log(_id, user,'Firebase Message Id')
const timestamp = new Date(numberStamp);
const message = {
_id,
timestamp,
text,
user: data.user,
friend
};
console.log(message, "Gifted")
return message;
}
};
on = callback =>
this.ref
.limitToLast(20)
.on('child_added', snapshot => callback(this.parse(snapshot)));
get timestamp() {
return firebase.database.ServerValue.TIMESTAMP;
}
// send the message to the Backend
send = messages => {
for (let i = 0; i < messages.length; i++) {
const { text, user } = messages[i];
const message = {
text,
user,
friend: this.state.friendID,
timestamp: this.timestamp,
};
this.append(message);
}
};
append = message => this.ref.push(message);
// close the connection to the Backend
off() {
this.ref.off();
}
get user() {
return {
name: auth().currentUser.displayName,
_id: this.uid
};
}
render() {
<GiftedChat
text={this.state.text}
onInputTextChanged={text => this.setState({ text: text })}
messages={this.state.messages}
isAnimated
onSend={messages => this.send(messages)}
user={this.user}
renderActions={this.renderCustomActions}
/>
);
}
}
I want a one to one chat created with firebase and react-native-gifted-chat
It's essentially the same except you limit it to just two people. This article explains more on how to handle one to one chat https://medium.com/#edisondevadoss/react-native-chat-using-firebase-d4c0ef1ab0b5