Firebase 'collection' is not exported from 'firebase/firestore' - javascript

I'm trying to import "collection" on my project, but I got this error only on "collection". I followed the firebase docs about query, but I've no idea how to solve it.
React:
import { query, where, getDocs, collection } from "firebase/firestore";
const [username, setUsername] = useState("")
const [utente, setUtente] = useState(null)
const [err, setErr] = useState(false)
const handleSearch = async () =>{
const q = query(collection(db, "users"), where("displayName", "==", username)
);
const querySnapshot = await getDocs(q);
querySnapshot.forEach((doc) => {
// doc.data() is never undefined for query doc snapshots
console.log(doc.id, " => ", doc.data());
});};
const handleKey = e=>{
e.code === "Enter" && handleSearch();
};
Package.json:
{
"name": "whatsapp-clone",
"version": "0.1.0",
"private": true,
"dependencies": {
"#emotion/react": "^11.10.4",
"#emotion/styled": "^11.10.4",
"#material-ui/core": "^4.11.4",
"#material-ui/icons": "^4.11.2",
"#mui/material": "^5.10.5",
"compressorjs": "^1.0.7",
"emoji-picker-react": "^3.6.2",
"firebase": "^8.6.3",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-firebase-hooks": "^3.0.4",
"react-router-dom": "^5.2.0",
"react-scripts": "4.0.3",
"react-scrollable-feed": "^1.3.1",
"uuid": "^8.3.2"
},
Thank you very much in advance

You are using Firebase 8.6.3 but the modular syntax was introduced starting from v9.0.0. Upgrading to latest version should fix the issue:
npm i firebase#latest
You can alternatively use the Namespaced syntax with the current version but I'll recommend upgrading and using the new one.

Related

ReferenceError: exports is not defined in ES module scope

I am new in typescript, when I compiled code it compiled properly but when I run program using node
I got this error ReferenceError: exports is not defined in ES module scope
ReferenceError: exports is not defined in ES module scope
This file is being treated as an ES module because it has a '.js' file extension and 'D:\projects\pro8\package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
at file:///D:/projects/pro8/await.js:40:1
at ModuleJob.run (node:internal/modules/esm/module_job:185:25)
at async Promise.all (index 0)
at async ESMLoader.import (node:internal/modules/esm/loader:281:24)
at async loadESM (node:internal/process/esm_loader:88:5)
at async handleMainPromise (node:internal/modules/run_main:65:12)
typescript code
import fetch from "node-fetch";
const baseApi = "https://reqres.in/api/users?page=1";
const userApi = "https://reqres.in/api/user";
interface Employee {
id: number
employee_name: string
employee_salary: number
employee_age: number
profile_image: string
}
const fetchAllEmployees = async (url: string): Promise<Employee[]> => {
const response = await fetch(url);
const { data }:any = await response.json();
return data;
};
const fetchEmployee = async (url: string, id: number): Promise<Record<string, string>> => {
const response = await fetch(`${url}/${id}`);
const { data }:any = await response.json();
return data;
};
const generateEmail = (name: string): string => {
return `${name.split(" ").join(".")}#company.com`;
};
const runAsyncFunctions = async () => {
try {
const employees = await fetchAllEmployees(baseApi);
Promise.all(
employees.map(async user => {
const userName = await fetchEmployee(userApi, user.id);
const emails = generateEmail(userName.name);
return emails;
})
);
} catch (error) {
console.log(error);
}
};
runAsyncFunctions();
package.json
{
"name": "pro8",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#typescript-eslint/eslint-plugin": "^5.21.0",
"#typescript-eslint/parser": "^5.21.0",
"eslint": "^8.14.0",
"eslint-config-standard": "^17.0.0",
"eslint-plugin-import": "^2.26.0",
"eslint-plugin-n": "^15.2.0",
"eslint-plugin-promise": "^6.0.0"
},
"dependencies": {
"#types/node-fetch": "^2.6.1",
"node-fetch": "^3.2.4"
}
}
I tried to solve this error ts An async function or method in ES5/ES3 requires the 'Promise' constructor
any answer not working in my case
so please give me solution if any
Try and remove "type": "module" from package.json. I had this issue before and it seemed to do the trick.

TypeError: querySnapshot.forEach is not a function - Firebase Cloud Functions

I have a data structure made this way:
Posts(collection)
UserId(document)
Posts(collection)
postDoc (document)
And I'm setting a cloud function to change all Posts(subcollection) documents upon a certain event, and in order to do so I'm using collectionGroup queries:
This is how I set it up:
exports.changeIsVisibleFieldAfterDay = functions.pubsub
.schedule("every 2 minutes").onRun((context) => {
const querySnapshot = db.collectionGroup("Posts")
.where("isVisible", "==", true).get();
querySnapshot.forEach((doc) => {
console.log(doc.data());
});
});
In the Firebase Log I receive the following error:
TypeError: querySnapshot.forEach is not a function
Searching online I found out that there may be a problem with Firebase SDK version but mine is uptodate, I attach the package.json file here:
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"scripts": {
"lint": "eslint .",
"serve": "firebase emulators:start --only functions",
"shell": "firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"engines": {
"node": "12"
},
"main": "index.js",
"dependencies": {
"firebase-admin": "^9.2.0",
"firebase-functions": "^3.11.0"
},
"devDependencies": {
"eslint": "^7.6.0",
"eslint-config-google": "^0.14.0",
"firebase-functions-test": "^0.2.0"
},
"private": true
}
The get() method is asynchronous, so you either need to use then() to get the querySnapshot when the Promise returned by get() is fulfilled, or use async/await. More details on how to deal with asynchronous calls in this SO answer.
With then()
const functions = require('firebase-functions');
// The Firebase Admin SDK to access Firestore.
const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore();
exports.changeIsVisibleFieldAfterDay = functions.pubsub
.schedule("every 2 minutes").onRun((context) => {
return db.collectionGroup("Posts").where("isVisible", "==", true).get()
.then(querySnapshot => {
querySnapshot.forEach((doc) => {
console.log(doc.data());
});
return null;
})
});
With async/await
const functions = require('firebase-functions');
// The Firebase Admin SDK to access Firestore.
const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore();
exports.changeIsVisibleFieldAfterDay = functions.pubsub
.schedule("every 2 minutes").onRun(async (context) => {
const querySnapshot = await db.collectionGroup("Posts").where("isVisible", "==", true).get();
querySnapshot.forEach((doc) => {
console.log(doc.data());
});
return null;
});
Note the return null; at the end. See this doc item for more details on this key point.
Note also that if you want to update several docs within the forEach() loop, you will need to use Promise.all(). Many SO answers cover this case.

React-Native app doesn't work if i use await

This is the first time I'm using react-native to develop an Android app.
I'm trying to use async/await when I retrieve some data from firestore, but when I add the word await the app crashes and it won't start anymore.
I use react-native-firebase library as you can see in my package.json file.
This is the part of my component that doesn't work:
componentDidMount() {
this.getAccountFromFirestore(this.props.user);
}
getAccountFromFirestore = async user => {
const accounts = await firebase
.firestore()
.collection('accounts')
.get();
this.setState({ loading: false });
};
This is my package.json, if it's usefull
{
"name": "myapp",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start",
"test": "jest",
"ios": "react-native run-ios",
"android": "react-native run-android"
},
"dependencies": {
"native-base": "^2.8.1",
"react": "16.6.1",
"react-native": "0.57.6",
"react-native-firebase": "^5.1.1",
"react-native-navigation": "^1.1.493",
"react-native-vector-icons": "^6.1.0",
"react-redux": "^5.1.1",
"redux": "^4.0.1"
},
"devDependencies": {
"babel-jest": "23.6.0",
"jest": "23.6.0",
"metro-react-native-babel-preset": "0.49.2",
"react-test-renderer": "16.6.1"
},
"jest": {
"preset": "react-native"
}
}
You can implement with Promise like :
firebase
.firestore()
.collection('accounts')
.get()
.then(accounts => {
console.log ('Use accounts variable as per your requirement,'accounts)
})
.catch(error => {console.error(error)})
I don't know whether it's your React Native or if you're using Node 6. But for what I know, async/await is only supported on Node 8 or above. So, your best bet is still using Promises with this problem. For example:
componentDidMount() {
this.getAccountFromFirestore(this.props.user);
}
getAccountFromFirestore = user => {
firebase
.firestore()
.collection('accounts')
.get()
.then(accounts => {
let data = accounts.docs.map(account => account.data());
console.log(data);
this.setState({ loading: false });
})
.catch(err => console.log(err));
};
Also when using async/await, don't forget the try-catch blocks:
componentDidMount() {
this.getAccountFromFirestore(this.props.user);
}
getAccountFromFirestore = async user => {
try {
const accounts = await firebase
.firestore()
.collection('accounts')
.get();
const data = accounts.docs.map(a => a.data());
console.log(data);
this.setState({ loading: false });
} catch (err) {
console.error(err);
}
};
Option a) keep using promises
Option b) Migrate that RN, if you can use async/await your code is prob too old to go in the stores anyway.
Option c) Babel...

Why is my Mocha/Chai test giving a false positive?

As a pre-cursor to this question, I am a novice at Node, JS, Mocha and Chai!
I have a set of tests which I run using npm run start, in which 'start' defines a script within my Package.json file:
"devDependencies": {
"chai": "^3.5.0",
"chai-as-promised": "^7.1.1",
"cli-color": "^1.1.0",
"concurrently": "^3.1.0",
"mocha": "^5.2.0"
},
"dependencies": {
"body-parser": "^1.16.1",
"cors": "^2.8.1",
"express": "^4.14.0",
"moment": "^2.18.1",
"superagent": "^3.3.2"
}
Here is my test:
const expect = require('chai').expect;
const screenshotFolder = 'puppeteer/test/screenshots';
module.exports = async(page) => {
const frame = page.frames().find(frame => frame.name() === 'iframe');
const allChoicesButton = await frame.$('.statement a.all-choices');
await allChoicesButton.click({});
const saveYourChoicesButton = await frame.$('.button.permissions-block__submit');
await saveYourChoicesButton.click({});
try {
const confirmationMessageText = await frame.$eval('.submission-response__copy > p', e => e.textContent);
describe('User can choose all', function() {
it('Click choose all and display a confirmation message', function(done) {
expect(confirmationMessageText).to.equal('Thank you. Your choices have been updatedx.').
notify(done)
});
});
} catch (err) {
await page.screenshot({
path: screenshotFolder + '/confirmationMessageText.png',
fullPage: true
});
}
};
I have purposefully added an 'x' to 'updatedx' so it fails....only it passes. So, I'm sure this has been asked 100 times but I'm unclear as to why it is passing and also why the screenshot is printed, given that an error is not thrown.
Thanks in advance.
I've realised the error now, swapped frame.$eval with frame.$ and this has resolved the issue.

Cannot read property 'functionName' of undefined

I am working on a react native project where I am trying to retrieve an array of json objects. I am currently using the fetch function like so:
//******************* require in root App.js ***********
global.fetch = require('isomorphic-fetch');
//******************* API.js *************************
import fetch from 'isomorphic-fetch';
const api = {
getData() {
const url = 'http://.php?route=users';
return fetch(url).then((res) => res.json());
}
};
export { api };
//****************** dataRetrieval.js *********************
//imports
import api.js form './filepath.js';
constructor(props) {
super(props);
this.state = {
email: '',
password: '',
error: '',
loading: false,
users: []
};
}
componentDidMount() {
api.getData(this).then((res) => {
this.setState({ users: res.getData });
});
}
Project Dependencies:
"dependencies": {
"axios": "^0.18.0",
"eslint-config-rallycoding": "^3.2.0",
"isomorphic-fetch": "^2.2.1",
"node-fetch": "^2.2.0",
"npm": "^6.4.1",
"react": "16.4.1",
"react-native": "0.56.0",
"react-native-fetch": "^2.0.0",
"react-navigation": "^2.12.1",
"unfetch": "^3.1.1"
},
When I try and run the simulator I recieve an error saying that my getData() function is undefined and cannot be read.
You're incorrectly using export/import.
Either use export default api in your API.js file, or use import { api } from './filepath.js' in your dataRetrieval.js file.
Then, Adding the upper answer, you should write the .catch.
it's not relevance your error, but have to get into the habit.
import fetch from 'isomorphic-fetch';
const api = {
getData() {
const url = 'http://.php?route=users';
return fetch(url)
.then((res) => res.json())
.catch(err=> console.log(err)
}
};
You can check for this

Categories

Resources