firebaseApp is not defined in firebase file - javascript

My firebase has some problems which the console says firestore is undefined. I think the problem actually comes from my firebaseApp or somewhere but i don't know how to fix it. it'd be kind of you guys to help me! Thank you so much!
This is my firebase.js:
import firebase from 'firebase';
const firebaseApp = firebase.initializeApp[{
apiKey: "<API_KEI>",
authDomain: "<PROJECT_ID>.firebaseapp.com",
projectId: "<PROJECT_ID>",
storageBucket: "<PROJECT_ID>.appspot.com",
messagingSenderId: "<SENDER_ID>",
appId: "<APP_ID>",
measurementId: "<MESURMENT_ID>"
}];
const db = firebaseApp.firestore();
const auth = firebase.auth();
export {
auth,
db
};
This is my SignIn.js:
import React from "react";
import firebase from "firebase";
import {
auth
} from "../firebase.js";
function SignIn() {
function signInWithGoogle() {
const provider = new firebase.auth.GoogleAuthProvider();
auth.signInWithPopup(provider);
}
return ( <
div >
<
button onClick = {
signInWithGoogle
} > Sign in with google < /button>{" "} <
/div>
);
}
This is my App.js:
import React from 'react'
import SignIn from './components/SignIn'
import Chat from './components/Chat'
function App() {
return ( <
div >
<
SignIn / >
<
Chat / >
<
/div>
)
}
export default App
This is my package.json:
{
"name": "image-search",
"version": "0.1.0",
"private": true,
"dependencies": {
"#emotion/react": "^11.4.1",
"#emotion/styled": "^11.3.0",
"#fortawesome/fontawesome-free": "^5.15.4",
"#material-ui/core": "^4.12.3",
"#material-ui/icons": "^4.11.2",
"#mui/icons-material": "^5.0.1",
"#mui/material": "^5.0.1",
"#testing-library/jest-dom": "^5.14.1",
"#testing-library/react": "^11.2.7",
"#testing-library/user-event": "^12.8.3",
"firebase": "^8.10.0",
"font-awesome": "^4.7.0",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-firebase-hooks": "^3.0.4",
"react-scripts": "4.0.3",
"uuidv4": "^6.2.12",
"web-vitals": "^1.1.2"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"#babel/preset-react": "^7.14.5"
}
}

You can use latest firebase and check the docs below.
In your code, const db = firebaseApp.firestore();, but latest version use const db = getFirestore(app); to initialize db.
This is a demo from official network.
import { initializeApp } from 'firebase/app';
import { getFirestore, collection, getDocs } from 'firebase/firestore/lite';
// Follow this pattern to import other Firebase services
// import { } from 'firebase/<service>';
// TODO: Replace the following with your app's Firebase project configuration
const firebaseConfig = {
//...
};
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
// Get a list of cities from your database
async function getCities(db) {
const citiesCol = collection(db, 'cities');
const citySnapshot = await getDocs(citiesCol);
const cityList = citySnapshot.docs.map(doc => doc.data());
return cityList;
}
And find more information in this page firebase

Related

Firebase error Cannot find module 'firebase/app' on React 18

I already used Firebase on another app recently. But this time I'm getting that error on console.
It's throwing this error on page
ERROR in ./src/Context/AuthContext.jsx 8:0-49
ERROR in ./src/Firebase.js 4:0-45
and this on console
bundle.js:1861 Uncaught Error: Cannot find module 'firebase/app'
at webpackMissingModule (bundle.js:1861:50)
at ./src/Firebase.js (bundle.js:1861:137)
at options.factory (bundle.js:126646:31)
at webpack_require (bundle.js:126092:33)
at fn (bundle.js:126303:21)
at ./src/Context/AuthContext.jsx (bundle.js:1641:67)
at options.factory (bundle.js:126646:31)
at webpack_require (bundle.js:126092:33)
at fn (bundle.js:126303:21)
at ./src/App.js (bundle.js:20:78)
This is my Firebase.js file
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
import { getFirestore } from "firebase/firestore";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,
projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.REACT_APP_FIREBASE_MESSAGING_SENDER,
appId: process.env.REACT_APP_FIREBASE_APP_ID,
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
export const auth = getAuth(app);
export const db = getFirestore(app);
export default app;
And this provider context file
import { createContext, useContext, useState, useEffect } from "react";
import { auth, db } from "../Firebase";
import { doc, setDoc } from "firebase/firestore";
import {
createUserWithEmailAndPassword,
signInWithEmailAndPassword,
signOut,
onAuthStateChanged,
} from "firebase/auth";
const UserContext = createContext();
export const AuthContextProvider = ({ children }) => {
const [user, setUser] = useState({});
const signUp = (email, password) => {
createUserWithEmailAndPassword(auth, email, password);
return setDoc(doc(db, "users", email), {
favList: [],
});
};
const signIn = (email, password) => {
return signInWithEmailAndPassword(auth, email, password);
};
const logout = () => {
return signOut(auth);
};
useEffect(() => {
const unsubscribe = onAuthStateChanged(auth, (currentUser) => {
setUser(currentUser);
});
return () => {
unsubscribe();
};
}, []);
return (
<UserContext.Provider value={{ signUp, signIn, logout, user }}>
{children}
</UserContext.Provider>
);
};
export const UserAuth = () => {
return useContext(UserContext);
};
package.json
{
"name": "cryptotracker-app",
"version": "0.1.0",
"private": true,
"dependencies": {
"#testing-library/jest-dom": "^5.16.5",
"#testing-library/react": "^13.4.0",
"#testing-library/user-event": "^13.5.0",
"axios": "^1.3.1",
"dompurify": "^2.4.3",
"firebase": "^9.17.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-icons": "^4.7.1",
"react-router-dom": "^6.8.0",
"react-scripts": "5.0.1",
"react-sparklines": "^1.7.0",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"tailwindcss": "^3.2.4"
}
}
I tried most of things like uninstall and install but they didn't work.
I am also getting the same error,but after removing the firebase version 9.17.0 and reinstalling firebase with its 9.16.0 vesrion all the error has been resolved.
Latest version of firebase might be unstable.

Firestore Import Error When In Jest With Next.JS

I am trying to run a test in next.js using jest that imports firebase, but i keep getting an error:
{import { registerVersion } from '#firebase/app'; SyntaxError: Cannot use import statement outside a module
Importing other modules works, but firebase throughs that error. I have tried other enviroments but none seem to work and either throw this error or another error.
Package.JSON:
{
"name": "chat",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint",
"test": "jest --forceExit --watchAll --coverage"
},
"dependencies": {
"#firebase/testing": "^0.20.11",
"firebase": "^9.9.4",
"kill-port": "^2.0.1",
"next": "12.2.5",
"react": "18.2.0",
"react-dom": "18.2.0",
"react-firebase-hooks": "^5.0.3",
"react-hot-toast": "^2.3.0",
"uuid": "^8.3.2"
},
"devDependencies": {
"#babel/plugin-syntax-jsx": "^7.18.6",
"#babel/preset-react": "^7.18.6",
"#firebase/rules-unit-testing": "^2.0.4",
"#testing-library/jest-dom": "^5.16.5",
"#testing-library/react": "^13.4.0",
"#types/jest": "^29.0.2",
"eslint": "8.23.0",
"eslint-config-next": "12.2.5",
"firebase-admin": "^11.0.1",
"jest": "^29.0.3",
"jest-environment-jsdom": "^29.0.3"
}
}
Jest.config.js:
// jest.config.js
const nextJest = require('next/jest');
const createJestConfig = nextJest({
// Provide the path to your Next.js app to load next.config.js and .env files in your test environment
dir: './',
});
// Add any custom config to be passed to Jest
/** #type {import('jest').Config} */
const customJestConfig = {
// Add more setup options before each test is run
// setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
// if using TypeScript with a baseUrl set to the root directory then you need the below for alias' to work
//moduleDirectories: ['node_modules', '<rootDir>/'],
testEnvironment: 'jest-environment-jsdom',
};
// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
module.exports = createJestConfig(customJestConfig);
test/page.test.js
/**
* #jest-environment jest-environment-jsdom
*/
import React from 'react';
import { render, screen } from '#testing-library/react';
import Thing from '../../pages/thing.jsx';
describe('testing Home page', () => {
test('render h1 element', () => {
expect(render(<Thing />));
});
});
pages/test.jsx
import { firestore } from "../lib/firebase";
export default function Thing({ }) {
return (
<main>
</main>
);
}
lib/firebase (Note: removed config fields)
import { initializeApp } from 'firebase/app';
import { getAuth, GoogleAuthProvider } from 'firebase/auth';
import { getFirestore } from 'firebase/firestore';
import { getStorage } from 'firebase/storage';
const firebaseConfig = {
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: ""
};
const app = initializeApp(firebaseConfig);
export const auth = getAuth(app);
export const googleAuthProvider = new GoogleAuthProvider();
export const firestore = getFirestore(app);
export const storage = getStorage(app);

Tailwindcss does not get loaded in react application

I am using the following packages and have installed tailwindcss in the following project folder /home/admin/Desktop/Code/main_project/client/package.json:
{
"name": "react-app",
"version": "1.0",
"private": true,
"dependencies": {
"babel-eslint": "10.0.3",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-redux": "^7.2.4",
"react-router": "^6.3.0",
"react-scripts": "3.2.0",
"redux": "^4.1.1",
"redux-thunk": "^2.3.0",
"web-vitals": "^1.0.1",
"web3": "^1.6.1",
"web3-eth-contract": "^1.5.2"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"autoprefixer": "^10.4.7",
"postcss": "^8.4.14",
"tailwindcss": "^3.0.24"
}
}
My tailwind.config.js looks like the following:
module.exports = {
content: [
"./src/**/*.{js,jsx,ts,tsx}",
],
theme: {
extend: {},
},
plugins: [],
}
As you can see my react-project lies in a subfolder.
My postcss.config.js looks like the following:
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
This is my index.css:
#tailwind base;
#tailwind components;
#tailwind utilities;
In my index.js I am loading my index.css:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import store from "./redux/store";
import { Provider } from "react-redux";
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById("root")
);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
serviceWorker.unregister();
My App.js looks like the following:
import React, { useEffect, useState, useRef } from "react";
import { useDispatch, useSelector } from "react-redux";
import { connect } from "./redux/blockchain/blockchainActions";
import { fetchData } from "./redux/data/dataActions";
import "./App.css";
function App() {
const dispatch = useDispatch();
const blockchain = useSelector((state) => state.blockchain);
const data = useSelector((state) => state.data);
const [CONFIG, SET_CONFIG] = useState({
CONTRACT_ADDRESS: "",
SCAN_LINK: "",
NETWORK: {
NAME: "",
SYMBOL: "",
ID: 0,
},
NFT_NAME: "",
SYMBOL: "",
MAX_SUPPLY: 1,
WEI_COST: 0,
DISPLAY_COST: 0,
GAS_LIMIT: 0,
MARKETPLACE: "",
MARKETPLACE_LINK: "",
SHOW_BACKGROUND: false,
});
const getData = () => {
if (blockchain.account !== "" && blockchain.smartContract !== null) {
dispatch(fetchData(blockchain.account));
}
};
const getConfig = async () => {
const configResponse = await fetch("/config/config.json", {
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
});
const config = await configResponse.json();
SET_CONFIG(config);
};
useEffect(() => {
getConfig();
}, []);
useEffect(() => {
getData();
}, [blockchain.account]);
return (
<>
<h1 className="text-3xl font-bold underline">Welcome</h1>
<>
);
}
export default App;
However, the components in my App.js do not get rendered with tailwindcss.
Any suggestions what I am doing wrong?
I appreciate your replies!

TypeError: [setState with createContext] is not a function - React

I am using React's Context API to call setCurrentUser below. But it gives me this error:
TypeError: setCurrentUser is not a function.
Upon logging console.log(useContext(globalContext)), I get the empty object {}.
I have manually converted my project from TS(where it worked by specifying setCurrentUser as type Dispatch) to JS, so I am not sure if that broke something...at least my react and react-dom packages should be current.
How do we make this work with JS? Thanks
Router.jsx - where I am calling setCurrentUser
import React, { useContext, useEffect } from "react";
import { BrowserRouter, Route, Switch } from "react-router-dom";
import LoginPg from "../pages/LoginPg/LoginPg";
import ErrorHandler from "./ErrorHandler";
import ErrorPg from "../pages/ErrorPg/ErrorPg";
import useGet from "../../server_api/useGet";
import ProtectedRoute from "./ProtectedRoute";
import HomePg from "../pages/HomePg/HomePg";
import { globalContext } from "../../store/context/globalContext";
import CalendarPg from "../pages/Calendar/CalendarPg";
function Router() {
const { currentUser, setCurrentUser } = useContext(globalContext);
const [doGet] = useGet();
let user;
console.log(useContext(globalContext)); // <==== logs: {}
useEffect(() => {
doGet("auth/authenticate", (res) => {
if (res) {
user = res.username;
setCurrentUser(res);
} else {
console.log("Router: user not authenticated");
}
});
}, []);
return (
<BrowserRouter>
<ErrorHandler>
<Switch>
<Route path="/error" component={ErrorPg} />
<Route path="/login" component={LoginPg} />
<ProtectedRoute
path="/calendar"
Component={CalendarPg}
isAuth={currentUser}
key="uniquevalue"
/>
<ProtectedRoute path="/" Component={HomePg} isAuth={currentUser} />
</Switch>
</ErrorHandler>
</BrowserRouter>
);
}
export default Router;
globalContext.jsx
import { createContext, useState } from "react";
export const globalContext = createContext({});
export default function GlobalContext(props) {
const [currentUser, setCurrentUser] = useState(null);
return (
<globalContext.Provider value={{ currentUser, setCurrentUser }}>
{props.children}
</globalContext.Provider>
);
}
package.json
{
"name": "test",
"version": "0.1.0",
"private": true,
"homepage": "/",
"dependencies": {
"#fullcalendar/daygrid": "^5.9.0",
"#fullcalendar/interaction": "^5.9.0",
"#fullcalendar/react": "^5.9.0",
"#fullcalendar/timegrid": "^5.9.0",
"#testing-library/jest-dom": "^5.11.4",
"#testing-library/react": "^11.1.0",
"#testing-library/user-event": "^12.1.10",
"antd": "^4.16.13",
"axios": "^0.21.1",
"bootstrap": "^5.1.1",
"font-awesome": "^4.7.0",
"fullcalendar": "^5.9.0",
"lodash": "^4.17.21",
"moment": "^2.29.1",
"query-string": "^4.3.4",
"react": "^17.0.2",
"react-calendar": "^3.4.0",
"react-dom": "^17.0.2",
"react-helmet": "^6.1.0",
"react-modal": "^3.14.3",
"react-router-dom": "^5.2.0",
"react-scripts": "4.0.3",
"sass": "^1.39.2",
"web-vitals": "^1.0.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"cypress": "npx cypress open"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"cypress": "^7.5.0"
}
}
You need the consumer (Router) to be a child of the provider (GlobalContext).
Also your component names should start with an Upper case.
import { GlobalContext } from "../../store/context/GlobalContext";
const App = () => {
const [currentUser, setCurrentUser] = useState(DEFAULT_USER);
return (
<GlobalContext.Provider value={{ currentUser, setCurrentUser }}>
<Router />
</GlobalContext.Provider>
);
};

Electron distribution build displays a blank page

I am working now upon an Electron + React-JS app, and have to create a distribution build. The problem is that after creating that build and launching the resulted file (in our case the compiled app), the app shows me a blank screen without rendering any of ./src folder's content. Everything's working well when launching Electron in dev mode.
For some reference, I'll attach the contents of my package.json, electron's main.js and React's index.js and App.js files.
Package.json
{
...
"build": {
"appId": ...,
"mac": {
"category": ...
},
"files": [
"build/**/*",
"node_modules/**/*"
],
"directories": {
"buildResources": "assets"
}
},
"main": "public/electron.js",
"homepage": "./",
"dependencies": {
"#reach/router": "^1.2.1",
"apexcharts": "^3.10.1",
"apisauce": "^1.1.1",
"cross-env": "^6.0.3",
"electron-is-dev": "^1.1.0",
"formik": "^2.0.4",
"moment": "^2.24.0",
"react": "^16.11.0",
"react-dom": "^16.11.0",
"react-loading-overlay": "^1.0.1",
"react-notification-system": "^0.2.17",
"react-pin-input": "^0.9.0",
"react-redux": "^7.1.3",
"react-scripts": "3.2.0",
"react-table": "^6.10.3",
"redux": "^4.0.4",
"redux-persist": "^6.0.0",
"reduxsauce": "^1.1.1",
"seamless-immutable": "^7.1.4",
"yup": "^0.27.0"
},
"scripts": {
"react-start": "react-scripts start",
"react-build": "react-scripts build",
"react-test": "react-scripts test --env=jsdom",
"react-eject": "react-scripts eject",
"electron-postinstall": "electron-builder install-app-deps",
"electron-start": "concurrently \"cross-env BROWSER=none yarn react-start\" \"wait-on http://localhost:3000 && electron .\"",
"electron-build": "electron-builder",
"release": "yarn react-build && electron-builder --publish=always",
"build": "yarn react-build && yarn electron-build",
"build-mw": "yarn react-build && electron-builder -mw"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"concurrently": "^5.0.0",
"electron": "^7.1.1",
"electron-builder": "^22.1.0",
"wait-on": "^3.3.0"
}
}
Electron main.js
const electron = require('electron');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
const path = require('path');
const url = require('url');
const isDev = require('electron-is-dev');
let mainWindow;
function createWindow() {
mainWindow = new BrowserWindow({width: 900, height: 680});
mainWindow.loadURL(isDev ? 'http://localhost:3000' : `file://${path.join(__dirname, '../build/index.html')}`);
mainWindow.on('closed', () => mainWindow = null);
}
app.on('ready', createWindow);
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
if (mainWindow === null) {
createWindow();
}
});
React index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
serviceWorker.unregister();
React App.js
import React from 'react';
import './App.css';
import {Provider} from 'react-redux';
import {createStore} from 'redux';
import {persistStore} from 'redux-persist';
import {PersistGate} from 'redux-persist/integration/react';
import Navigation from './Navigation';
import {RootReducer} from './Redux/Root.Reducer';
const store = createStore(RootReducer);
const persistor = persistStore(store);
function App() {
return (
<Provider store={store}>
<PersistGate loading={null} persistor={persistor}>
<Navigation />
</PersistGate>
</Provider>
);
}
export default App;
P.S. As opposed to the tutorials found on the internet about linking Electron with React-JS, I've placed Electron's main.js file under ./public directory, in my React project.

Categories