I can’t save data to the Firebase database - React Native

Asked

Viewed 347 times

1

I cannot save data in the Firebase database - React Native. I have already done the installation and import of Firebase in the project, the code is 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 this working out, only it doesn’t work when I call the method salvarDados, appears the following error:

inserir a descrição da imagem aqui

  • post your code, not photos of it, makes it easier to understand the problem

2 answers

1

The problem with your code is in componentWillMount(). Your App is not being initialized in its function surrender(). Causing the componentWillMount() not be executed.

Example of component initialization:

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

  render() {
    <App />
  }
}

The solution to this is you include Appregistry (it can be after the render function), then 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)
}
  • It didn’t work, you kept making the same mistake

  • putting firebase startup in the constructor as well?

  • yes, it is as if the firebase command is not active

  • this is all your code?

  • Yes, I made the imports like this: import firebase from '@firebase/app'; import '@firebase/firestore'; import '@firebase/auth';

  • to using firebase version 5.7.0 and React-Native version 0.57.7

Show 1 more comment

0

I was able to solve just by 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';

Browser other questions tagged

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