I can not save data in the Firebase database - React Native

1

I can not save data in the Firebase - React Native database. I have already installed and imported Firebase into the project, the code looks like this:

 componentWillMount(){
  var config = {
    apiKey: "***************************",
    authDomain: "configuracaofirebase-3a6ef.firebaseapp.com",
    databaseURL: "https://configuracaofirebase-3a6ef.firebaseio.com",
    projectId: "configuracaofirebase-3a6ef",
    storageBucket: "configuracaofirebase-3a6ef.appspot.com",
    messagingSenderId: "939162871117"
  };

  firebase.initializeApp(config);
}

salvarDados(){
  var database = firebase.database();
  database.ref("pontuacao").set("100");
}

render() {
  return (
    <View style={styles.container}>
      <Button 
        onPress={ () => { this.salvarDados() } }
        title="Salvar dados"
        color="#841584"
        accessibilityLabel="Salvar dados"
      />
      <Text>Meu App</Text>
    </View>
  );
}

The componentWillMount is working, it just does not work when I call the salvarDados method, the following error appears:

    
asked by anonymous 07.12.2018 / 14:50

2 answers

1

Your code problem is in componentWillMount () . Your App component is not being initialized in your render () function. Making the componentWillMount () not run.

Component initialization example:

export default class App extends component {
  componentWillMount() { . . . }

  render() {
    <App />
  }
}

The solution to this is to include AppRegistry (it can be after the render function), so your code will go through the componentWillMount ()

import { AppRegistry } from 'react-native';

AppRegistry.registerComponent('<NomeDoProjeto>', () => App);

If you do not want to use AppRegistry, you can include the firebase code in your constructor

constructor(props) {
  super(props);

  var config = { ... }
  firebase.initializeApp(config)
}
    
07.12.2018 / 16:01
0

I was able to solve this by just adding a new import.

It was like this: import firebase from '@ firebase / app';

Then I put it like this: import firebase from '@ firebase / app'; import '@ firebase / database';

    
07.12.2018 / 20:17