'How to give the user the ability to put a username in react native with firebase?
In my app so far(works like a todo list) i already set up the login and then the overall dashboard for them to create tasks in the app. However, On the top of the app im trying to add a text feild that allows them to write their username and not their auth.currentUser.email. However when i tried i to do this the text inputs value gets ereased when i log out. How would i be able to add a permanent solution for users to add their username?
Code:
import React, { useEffect } from 'react';
import {useState} from "react"
import { SafeAreaView, Text, View, Button, TouchableOpacity, Modal, StyleSheet,Pressable, TextInput,ImageBackground, Image, ScrollView, } from 'react-native';
import { collection, doc, setDoc, query, getDocs, onSnapshot, addDoc, orderBy, limit, Timestamp, where} from "firebase/firestore";
import {db} from "../firebase"
import { auth } from '../firebase';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { AntDesign } from '@expo/vector-icons';
import { Feather } from '@expo/vector-icons';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import Checkbox from 'expo-checkbox';
import {signPlsOut} from "../firebase"
export const Dashboard = () => {
const image = { uri: "https://cdn.discordapp.com/attachments/901614276748402820/946157600041476176/Screen_Shot_2022-02-23_at_4.32.16_PM.png" };
const {uid, photoURL, displayName, email} = auth.currentUser;
const [modalVisible, setModalVisible] = useState([]);
const [modalVisibleImage, setModalVisibleImage] = useState([])
const [projects, setProjects] = useState([])
const [desc, setDesc] = useState("");
const [title, setTitle] = useState("");
const todosref = collection(db, 'todosref')
const date = new Date().toLocaleString();
const emojiDataRaw = ["✌","😂","😝","😁","😱","👉","🙌","🍻","🔥","🌈","☀","🎈","🌹","💄","🎀","⚽","🎾","🏁","😡","👿","🐻","🐶","🐬","🐟","🍀","👀","🚗","🍎","💝","💙","👌","❤","😍","😉","😓","😳","💪","💩","🍸","🔑","💖","🌟","🎉","🌺","🎶","👠","🏈","⚾","🏆","👽","💀","🐵","🐮","🐩","🐎","💣","👃","👂","🍓","💘","💜","👊","💋","😘","😜","😵","🙏","👋","🚽","💃","💎","🚀","🌙","🎁","⛄","🌊","⛵","🏀","🎱","💰","👶","👸","🐰","🐷","🐍","🐫","🔫","👄","🚲","🍉","💛","💚"];
const item = emojiDataRaw[Math.floor(Math.random()*emojiDataRaw.length)];
const [profilename, setProfileName] = useState("")
const shadowColors = ["#FFD6A7", "#FF92B3", "#59F5D1", "#C1F1FE", "#A498FE"]
const shadowColor = shadowColors[Math.floor(Math.random()*shadowColors.length)];
useEffect(() => {
const getData = async () => {
const q = await query(todosref, where('uid', '==', uid), orderBy("createdAt"))
onSnapshot(q, (snapshot) => {
let todos = []
snapshot.forEach((doc) => {todos.push(doc.data())})
setProjects(todos)
})
}
getData()
}, [])
async function handleAddTask () {
try {
await addDoc(todosref, {
title: title,
desc: desc,
createdAt: Timestamp.fromDate(new Date()),
uid: uid,
})
setTitle("")
setDesc("")
setModalVisible(false)
}
catch(error) {
console.log('There has been a problem with your fetch operation: ' + error.message);
// ADD THIS THROW error
throw error;
}
}
return (
<>
<Modal
animationType="slide"
transparent={true}
visible={modalVisible}
onRequestClose={() => {
Alert.alert("Modal has been closed.");
setModalVisible(!modalVisible);
}}
>
<View style={styles.centeredView}>
<View style={styles.modalView}>
<Text style={styles.modalText}>Add task:</Text>
<View style={{marginBottom: 20}}>
<TextInput placeholder='title' value={title} onChangeText={(text) => setTitle(text)} style={{marginBottom: 20, fontSize: 20}}></TextInput>
<TextInput placeholder='description' value={desc} onChangeText={(text) => setDesc(text)}></TextInput>
</View>
<Pressable
style={[styles.button, styles.buttonClose]}
onPress={handleAddTask}
>
<Text style={styles.textStyle}>submit task</Text>
</Pressable>
<Pressable
style={[styles.cancel]}
onPress={() => setModalVisible(!modalVisible)}
>
<Text style={{color: "#000", fontSize: 20}}>Cancel</Text>
</Pressable>
</View>
</View>
</Modal>
<Modal
animationType="slide"
transparent={true}
visible={modalVisibleImage}
onRequestClose={() => {
Alert.alert("Modal has been closed.");
setModalVisible(!modalVisible);
}}
>
<View style={styles.centeredView}>
<View style={styles.modalView}>
<Text style={styles.modalText}>Change PFP</Text>
<View style={{display: "flex", flexDirection: "row", justifyContent: "space-between", marginBottom: 20}}>
<Image source={{uri: "https://cdn.discordapp.com/attachments/926690547253534740/952329304056946758/Screen_Shot_2022-03-12_at_5.16.26_PM.png"}}style={{
height: 60,
width: 60,
marginRight: 20,
borderRadius: 40
}}></Image>
<Image source={{uri: "https://cdn.discordapp.com/attachments/926690547253534740/952329352421449828/Screen_Shot_2022-03-12_at_5.16.46_PM.png"}}style={{
height: 60,
width: 60,
marginRight: 20,
borderRadius: 40
}}></Image>
<Image source={{uri: "https://cdn.discordapp.com/attachments/926690547253534740/952329388077228052/Screen_Shot_2022-03-12_at_5.16.56_PM.png"}}style={{
height: 60,
width: 60,
borderRadius: 40
}}></Image>
</View>
<Pressable
style={[styles.button, styles.buttonClose]}
onPress={() => setModalVisibleImage(!modalVisibleImage)}
>
<Text style={styles.textStyle}>Cancel</Text>
</Pressable>
</View>
</View>
</Modal>
<SafeAreaView style={{
flex: 1,
display: "flex",
justifyContent: 'space-between',
margin: 20,
flexDirection: "column",
}}>
<View style={{
flex: 1,
marginTop: 20
}}>
<View style={{marginBottom: 20, display: "flex", flexDirection: "row", justifyContent: "space-between"}}>
<View style={{display: "flex", flexDirection: "row"}}>
<Pressable onPress={() => setModalVisibleImage(true)}>
<Image source={{uri: "https://cdn.discordapp.com/attachments/856542608171073616/947245168191496212/Screen_Shot_2022-02-26_at_4.33.30_PM.png"}} style={{width: 50, height: 50}}></Image>
</Pressable>
<View style={{marginLeft: 20, display: "flex", justifyContent: "space-between"}}>
<TextInput style={{fontSize: 17, fontWeight: "700"}} value={displayName} onChangeText={(profilename) => {auth.currentUser.email = profilename}} placeholder="username_blank" placeholderTextColor="#9D9EA2"></TextInput>
<Text style={{color: "grey", fontSize: 15}}>Good Day 👋🏼</Text>
</View>
</View>
<View style={{display: "flex", flexDirection: "row", alignItems: "center"}}>
<AntDesign name="search1" size={24} color="black" />
<Feather name="bell" size={24} color="black" style={{marginLeft: 10}}/>
</View>
</View>
<View style={{display: "flex", flexDirection: "row", marginBottom: 20, alignSelf: "center"}}
><Text style={{marginRight: 10, fontSize: 27, fontWeight: "700"}}>{new Date().toLocaleString('en-US', {
weekday : 'long'
})}</Text>
<Text style={{marginRight: 5, fontSize: 27, fontWeight: "700"}}>
{new Date().toLocaleString('en-US', {
month : 'long'
})},</Text>
<Text style={{ fontSize: 27, fontWeight: "700"}}>{new Date().getDate()}th</Text>
</View>
<ScrollView style={{
flex: 1, padding: 10, borderRadius: 20, marginBottom: 20,
backgroundColor: "#F5F4F7", position: "relative"
}}>
<Text style={{
fontSize: 20,
fontWeight: "700"
}}>Goals for Today</Text>
<View style={{display: "flex", flexDirection: "column"}}>
{projects.map((doc, key) => (
<View key={key} style={{
backgroundColor: shadowColor,
padding: 20,
marginTop: 20,
display: "flex",
flexDirection: "column",
justifyContent: "space-between",
borderWidth: 1,
borderRadius: 20,
borderColor: 'transparent',
borderBottomWidth: 0,
shadowColor: shadowColor,
shadowOffset: { width: 0, height: 0 },
shadowOpacity: 1,
shadowRadius: 20,
elevation: 3,
flex: 1,
}}>
<View style={{display: "flex", flexDirection: "row", alignItems: "center"}}>
<Text style={{}}>{item}</Text>
<Text style={{
fontSize: 26,
color: "#fff",
fontWeight: "700",
marginLeft: 10
}}>{doc.title}</Text>
</View>
<View>
<Text style={{
fontSize: 18 , color: "#fff",marginLeft: 34
}}>{doc.desc}</Text>
</View>
</View>
))}
</View>
<View style={{backgroundColor: "#4630EB", borderRadius: "20", padding: 10, alignSelf: "center", bottom: 0, left: 0, right: 0, marginTop: 100}}>
<Button title='Sign Out' onPress={signPlsOut} color="#fff" style={{
color: "#fff"
}}></Button>
</View>
</ScrollView>
</View>
<View style={{
display: "flex",
alignItems: "center",
justifyContent: "center",
flexDirection: "row",
}}>
<TouchableOpacity >
<Pressable
onPress={() => setModalVisible(true)}>
<AntDesign name="pluscircle" size={50} color="#8BF45B" />
</Pressable>
</TouchableOpacity>
</View>
</SafeAreaView>
</>
);
};
Solution 1:[1]
Using auth.currentUser.email = profilename won't change the email of the user. What you need is to save the profilename to firestore instead. For example, once the user is finish editing the username, save the username to firestore with path (usernames/${auth.currentUser.id}). Then when your app starts, fetch the document to get the saved username and use it as the initial value of profilename.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kevin |

