How to Fill in My Fields through My React-Native and (Firebase) Database

Asked

Viewed 900 times

0

How to Fill my Textinputs through my database so that the User can edit them and insert them again (replacing the old ones) for example:(take my email and password I have in BD and put in these Textsinputs to then edit and how to send again to BD), I am beginner and because of this I do not know how I could do correctly...

import React, {Component} from 'react';
import {View, Text, StyleSheet, Button, TextInput} from 'react-native';
import firebase from 'firebase';

export default class TelaLogin extends Component{

  constructor(props) {
          super(props);
          this.state = {
            cidadeINput:'',
            emailInput:'',
            estadoInput:'',
            nomeINput:'',
            senhaInput:'',
            usuarioInput:'',
          };

          let config = {
              apiKey: "AIzaSyBEAn6v3qKO8m7jEsO7JlpTAnsCvKSoevo",
              authDomain: "adote-ja.firebaseapp.com",
              databaseURL: "https://adote-ja.firebaseio.com/",
              projectId: "adote-ja",
              storageBucket: "adote-ja.appspot.com",
              messagingSenderId: "1081270881358"
          };
          firebase.initializeApp(config);

          this.inserirUsuario = this.inserirUsuario.bind(this);
  }

  inserirUsuario() {
      if( this.state.usuarioInput.length > 0 ){

          let usuarios = firebase.database().ref('usuarios');

          let chave = usuarios.push().key;

          usuarios.child(chave).set({
            usuario:this.state.usuarioInput,
            senha:this.state.senhaInput
          });
          alert("senha inserida")
      }
  }
        render(){
            return(
              <View style = {styles.container}>

                  <TextInput style={styles.input} placeholder="Usuário" onChangeText={(usuarioInput)=>this.setState({usuarioInput})} />

                  <TextInput style={styles.input} placeholder="Senha" onChangeText={(senhaInput)=>this.setState({senhaInput})} />

                    <Button title="inserir usuário" onPress={this.inserirUsuario} />
              </View>
            );
        }
}

const styles = StyleSheet.create({

  container:{
    flex: 1,
    marginTop: 20,
    padding: 20,
  },

  input:{
    height: 40,
    borderWidth: 1,
    borderColor: '#FF0000',
  },
});  

1 answer

1

Hello! First recommend not to leave data access to your database in Firebase exposed like this. I don’t know much about Firebase, but I believe that the call to the API is asynchronous, so you could use React’s life methods to get this data. We usually use the componentDidMout(){} where it is called after the component is called and there you can evolve the state and this will reflect in its component text.

Based on the first post that you placed the call to Firebase and that the name of the inputs is the name of your fields in the database, this would be just below your constructor method:

import React, {Component} from 'react';
import {View, Text, StyleSheet, Button, TextInput} from 'react-native';
import firebase from 'firebase';

export default class TelaLogin extends Component{

  constructor(props) {
          super(props);
          this.state = {
            cidadeINput:'',
            emailInput:'',
            estadoInput:'',
            nomeINput:'',
            senhaInput:'',
            usuarioInput:'',
          };

          let config = {
              apiKey: "AIzaSyBEAn6v3qKO8m7jEsO7JlpTAnsCvKSoevo",
              authDomain: "adote-ja.firebaseapp.com",
              databaseURL: "https://adote-ja.firebaseio.com/",
              projectId: "adote-ja",
              storageBucket: "adote-ja.appspot.com",
              messagingSenderId: "1081270881358"
          };
          firebase.initializeApp(config);

          this.inserirUsuario = this.inserirUsuario.bind(this);
  }
// Notei que você recebe só o nome na função, poderia retornar todos os dados tbm se necessário
  componentDidMount() {
    let data;
    firebase.database().ref("nome").on('value', (snapshot)=> data = snapshot.val() //poderia já setar o state aqui.)
    this.setstate({
            usuario: data,
    }) 
}


  inserirUsuario() {
      if( this.state.usuarioInput.length > 0 ){

          let usuarios = firebase.database().ref('usuarios');

          let chave = usuarios.push().key;

          usuarios.child(chave).set({
            usuario:this.state.usuarioInput,
            senha:this.state.senhaInput
          });
          alert("senha inserida")
      }
  }
        render(){
        const { usuario, senha } = this.state; //usando a desestruturação
            return(
              <View style = {styles.container}>

                  <TextInput style={styles.input} value={usuario} placeholder="Usuário" onChangeText={(usuarioInput)=>this.setState({usuarioInput})} />

                  <TextInput style={styles.input} placeholder="Senha" 
value={senha} onChangeText={(senhaInput)=>this.setState({senhaInput})} />

                    <Button title="inserir usuário" onPress={this.inserirUsuario} />
              </View>
            );
        }
}

See that I entered the attribute value inside Textinput. Detail is also that I do not know exactly the return of data that comes from firebase so I put there as I believe it is.

  • Friend, it was not quite this problem that I have, I need to bring the textsinputs filled by data from my BD so that the user can edit it dps and click update

  • Yes, to fill in the data coming from the database, the component needs to be mounted first and only after that you arrow the state with the data coming from the component. That’s why you use the ComponentDidMount to do this. place your function to fetch the data inside the compomentDidMout.

  • friend you could give me an example with the code for me to see/

  • write an example in code as it would be

  • I changed my first answer by adding the IdMount component. This is the answer, you just have to see if the method you use to call Firebase is right and if the data that is returned is the same. You may need to insert an Async/Await in the method.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.