The logic I have used when registering a user is to add their details to a path in the database as well as to Firebase authentication. In theory the values would be easier to manipulate. My goal is to create a Formik form that will accept the existing value of the username of the logged in user, display that in a Text Input for the user to change then update the value in Firebase database. Can anyone help?
import React, {Component} from 'react';
import {TextInput, View, Button, StyleSheet} from 'react-native';
import {Formik} from 'formik';
import Firebase from 'firebase';
import 'firebase/database';
import 'firebase/auth';
export default class ChangeUsername extends Component {
constructor(props) {
super(props);
this.state = {
currentUsername: '',
Username: '',
};
}
getUsername() {
const userKey = Firebase.auth().currentUser.uid;
const userRef = Firebase.database().ref('users/' + userKey);
userRef.once('value').then(snapshot => {
const user = snapshot.val();
this.setState({currentUsername: user.username});
console.log(this.state.currentUsername);
});
}
changeUsername() {
const userKey = Firebase.auth().currentUser.uid;
const userRef = Firebase.database().ref('users/' + userKey);
userRef.update({
username: this.state.Username,
});
console.log(this.state.Username);
}
componentDidMount() {
this.getUsername();
this.changeUsername();
}
render() {
return (
<View>
<Formik
initialValues={{
username: this.state.currentUsername,
}}
enableReinitialize={true}
onSubmit={this.changeUsername()}>
{props => (
<View>
<TextInput
style={style.txtInput}
onChangeText={text => this.setState({Username: text})}
value={this.state.currentUsername}
/>
<Button title="Submit" onPress={props.handleSubmit} />
</View>
)}
</Formik>
</View>
);
}
}
I have also attempted creating the form with a React functional component as opposed to a class. What is currently happening is the Text Input remains empty and will revert back to empty everytime I try to type something in it. Plus, the username in the database will be updated to the letter I manage to type in before it disappears. I.e. I type the letter "p", the username will be updated to the string "p" in firebase database then the text input will be cleared.