Home > Net >  Retrieving Firebase Data in a config.js file for React Native Expo App
Retrieving Firebase Data in a config.js file for React Native Expo App

Time:09-29

I've been developing a React Native Expo App which is compatible with both iOS and Android devices. In this app I need to retrieve and render data from my google firebase database.

I would like to rewrite my firebase code into a config.js file as currently I have the firebase script inside each App screen which is causing issues. Instead, I want to write a config.js file which exports the data, allowing me to retrieve the data in each screen by the import statement:

import { CustomerData } from '../app/config.js';

The code below (minus the export statement) works just fine on each screen when I use the 'info' data retrieved. However this is causing issue when adding new features to screens and is an inefficient way to retrieve google firebase data.

I've attempted to write the config.js file like so:

import "firebase/firestore";
import * as firebase from "firebase";
import React, { useState, Component, useEffect } from "react";
import "react-native-gesture-handler";

const firebaseConfig = {
   apiKey: <My Api Key>,
   authDomain: <My AuthDomain>,
   projectId: <My Project Id>,
   storageBucket: <My storage Bucket>,
   messagingSenderId: <Sender Id>,
   appId: <App ID>,
   measurementId: <Measurement ID>,
 };

 if (!firebase.apps.length) {
   firebase.initializeApp(firebaseConfig);
 } else {
   firebase.app(); 
 }

 function GetData() {
   const [info, setInfo] = useState([]); // Initial empty array of info
 
   useEffect(() => {
     const dbh = firebase.firestore();
 
     dbh
       .collection("CustomerDatabase")
       .get()
       .then((querySnapshot) => {
         const info = [];
 
         querySnapshot.forEach((documentSnapshot) => {
           info.push({
             ...documentSnapshot.data(),
             key: documentSnapshot.id,
           });
         });
         setInfo(info);
       });
   }, []);

export info;

I believe I need to add an export function which exports the retrieved data - 'info'. However I have attempted to place this export statement in different locations in the script and it returns the error

SyntaxError: 'import' and 'export' may only appear at the top level. (44:0)

Even when placing the export statement at the start of the script I still receive the same error. Also when removing the export state it throws the error:

TransformError SyntaxError: Unexpected token (44:15) Indicating the last line as the culprit. This same code format works on the app screens however.

How would I export the 'info' data from within a config.js file? or do I have to stick to retrieving my firebase data from within each screens js file?

CodePudding user response:

I ran this code, and except for the fact that you forgot to add a curly brace to close your GetData funtion, there appears to be no other error

import "firebase/firestore";
import * as firebase from "firebase";
import React, { useState, Component, useEffect } from "react";
import "react-native-gesture-handler";

const firebaseConfig = {
   apiKey:"",
   authDomain:"",
   projectId:"",
   storageBucket:"",
   messagingSenderId:"",
   appId:"",
   measurementId:"",
 };

 if (!firebase.apps.length) {
   firebase.initializeApp(firebaseConfig);
 } else {
   firebase.app(); 
 }

 function GetData() {
   const [info, setInfo] = useState([]); // Initial empty array of info
 
   useEffect(() => {
     const dbh = firebase.firestore();
 
     dbh
       .collection("CustomerDatabase")
       .get()
       .then((querySnapshot) => {
         const info = [];
 
         querySnapshot.forEach((documentSnapshot) => {
           info.push({
             ...documentSnapshot.data(),
             key: documentSnapshot.id,
           });
         });
         setInfo(info);
       });
   }, []);

 }

export {info};

CodePudding user response:

It makes sense though because info is not a global variable, you declared info as a variable in GetData, so if you want it to be accessible you should return it in your GetData() function. Then you can now export GetData and you should get back info from the function.

import "firebase/firestore";
import * as firebase from "firebase";
import React, { useState, Component, useEffect } from "react";
import "react-native-gesture-handler";

const firebaseConfig = {
apiKey:"",
authDomain:"",
projectId:"",
storageBucket:"",
messagingSenderId:"",
appId:"",
measurementId:"",
};

if (!firebase.apps.length) {
firebase.initializeApp(firebaseConfig);
} else {
firebase.app(); 
}

function GetData() {

 const [info, setInfo] = useState([]); // Initial empty array of info
 
useEffect(() => {

const dbh = firebase.firestore();
 
dbh.collection("CustomerDatabase").get().then((querySnapshot) => {

const info = [];
 
querySnapshot.forEach((documentSnapshot) => {
info.push({
...documentSnapshot.data(),
key: documentSnapshot.id,
});
});

setInfo(info);

});
}, []);

return(info);

}

export {info};

//Then wherever you want to use info you can just do this...

import {GetData} from "filepath";

const info = GetData();

CodePudding user response:

Another way I like to export state in my react apps is to define the state in my App.js so it's accessible to every component in my app. Example of how I would export a state holding the theme for my app below. I pass my state ad its setter as a prop to my AppRouting Component. And then whenever I have a component I want to have access to the theme in my AppRouting, I just do this: theme={props.theme} setTheme={props.setTheme}

import { useState } from "react";
import { Box, ThemeProvider, } from "@mui/material";
import { darkTheme } from "./Theming/AppTheme";
import AppRouting from "./Pages/AppRouting";

const App = () => {

const [theme, setTheme] = useState(darkTheme);

return(

<ThemeProvider theme={theme}>
<Box
sx={{
position:"absolute",
width:"100vw",
height:"auto",
minHeight:"100vh",
top:"0",
left:"0",
display:"flex",
backgroundColor:"background.default",
}}
>
<AppRouting 
theme={theme}
setTheme={setTheme}
/>
</Box>
</ThemeProvider>

);

}

export default App;

  • Related