Inside my index.js file:
export function postArticleAPI(payload) {
return(dispatch) => {
const upload = storage
.ref(`images/${payload.image.name}`)
.put(payload.image);
upload.on("state_changed", (snapshot) => {
const progress = (
(snapshot.BytesTransferred / snapshot.totalBytes) * 100);
console.log(`Progress: ${progress}%`);
if(snapshot.state === "RUNNING") {
console.log(`Progress: ${progress}%`);
}
},
(error) => console.log(error.code),
async() => {
const downloadURL = await upload.snapshot.ref.getDownloadURL();
db.collection("articles").add({
...
});
});
}
};
}
I look in the docs provided by firebase but I am unsure how to implement that. When I run the code above, I get "TypeError: firebase__WEBPACK_IMPORTED_MODULE_0_.storage.ref is not a function" error.
I messed around with the code and I've also gotten other errors such as: "...storage.put is not a function," I've gotten errors with upload, as well as db.collection error.
Here's my firebase.js:
import { initializeApp } from 'firebase/app';
import { getAuth, GoogleAuthProvider } from 'firebase/auth';
import { getStorage } from "firebase/storage";
import { getFirestore } from "firebase/firestore";
const firebaseConfig = {
...
}
const firebaseApp = initializeApp(firebaseConfig);
const db = getFirestore(firebaseApp);
const auth = getAuth();
const provider = new GoogleAuthProvider();
const storage = getStorage(firebaseApp);
export { auth, provider, storage };
export default db;
Any help would be appreciated (and this is my first post, so please let me know if I need to add anything else). Thanks!
Since you're using the v9 syntax for importing top-level functions, there is no longer a storage.ref() method. Instead, as shown in the documentation on getting a reference and uploading files, you can do:
const ref = ref(storage, `images/${payload.image.name}`)
const upload = uploadBytes(ref, payload.image);
Related
Following code is from firebaseConfig.js:
import { initializeApp } from "firebase/app";
import { getAnalytics } from "firebase/analytics";
import { getAuth } from "firebase/auth";
const firebaseConfig = {
//credentials//
};
export const app = initializeApp(firebaseConfig);
export const analytics=getAnalytics(app)
export const authentication=getAuth(app);
Following code is from index.js:
export default function Home() {
const auth = getAuth();
const generateRecaptcha=()=>{
window.recaptchaVerifier = new RecaptchaVerifier('recaptcha-container', {}, authentication);
}
window.recaptchaVerifier = new RecaptchaVerifier('recaptcha-container', {}, auth);
const getOTP=()=>{
generateRecaptcha()
}
I am getting error:
ReferenceError: window is not defined
After removing export getAnyalytics, I am still getting the same error but at window.recaptchaVerifier function in index.js.
Also please tell me the use of getAnalytics.
getAnalytics() will instantiate an instance of Firebase Analytics that you can use to log events throughout your app.
The solution for me when using analytics was to create a provider as follows:
FirebaseTrackingProvider.tsx
export const FirebaseTrackingProvider = (props: {children: ReactNode}) => {
const router = useRouter();
const [analytics, setAnalytics] = useState(null);
useEffect(() => {
setAnalytics(getAnalytics(firebaseApp));
if (analytics) {
setAnalyticsCollectionEnabled(analytics, true);
}
const handleRouteChange = (url: string) => {
if (!analytics) {
return;
}
logEvent(analytics, 'page_view', {
page_location: url,
page_title: document?.title,
});
setCurrentScreen(analytics, document.title ?? 'Undefined');
};
router.events.on('routeChangeStart', handleRouteChange);
return () => {
router.events.off('routeChangeStart', handleRouteChange);
};
}, [analytics, router.events]);
return <FirebaseContext.Provider value={analytics}>{props.children}</FirebaseContext.Provider>;
};
I can then consume it different pages or components:
const analytics = useContext(FirebaseContext);
// in sign up flow
logEvent(analytics, 'sign_up', {
uid: data.uid,
email: data.email,
});
Regarding the recapture erorr: NextJS will first attempt to render serverside content if there is any, before bootstrapping the react application. This means that the window has not been defined yet when you are trying to instantiate a new RecaptchaVerifier instance. You can use an if(window) to make sure you are only doing so when the window is instantiated, or alternatively, you can run a useEffect as follows:
useEfect(() => {
// This wont change on re renders
let completed = false;
if (!completed && window){
// recaptca instantiation
completed = true;
}
}, [window])
here's the jist of where I'm stuck (or just read the title for my question).
I have a firebase.js file where I have functions to authenticate. signinGithub, signinGoogle, signinEmail and so forth. The Firebase Auth business logic is in these functions.
I am showing errors with console.log or alert from these functions. The functions are imported into a Component and I don't know how to capture the functions result into the component by somehow setting state from this out-of-component function file.
Here's a basic example:
firebase.js
...
const signInWithGitHub = async () => {
try {
const res = await signInWithPopup(auth, githubProvider)
const user = res.user
} catch (err) {
alert(err) // ** I want to pass "err" from here to Login
// ** component by updating Logins state for a message
}
}
export {signinWithGitHub}
...
Login.jsx
import React, { useEffect, useState } from "react"
import { useAuthState } from "react-firebase-hooks/auth"
import {
auth,
signInWithGitHub
} from "../lib/firebase"
function Login() {
const [user, loading, error] = useAuthState(auth)
render(
{* Below is the method call from the imported custom firebase function *}
<button onClick={signInWithGitHub}>
Login with GitHub
</button>
)
}
...
I was thinking something like this but I can't fully resolve it in my mind:
Set state in Login.js const [message, setMessage] = useState('')
When the imported signinWithGitHub has an error message --
I'm stuck figuring out how to apply to function message to the state, any ideas?
You can create a custom function inside your Login. jsx file to call the original signInWithGitHub method with a try catch block. And more importantly, you should not use render inside a functional component. Use return to render the JSX in DOM.
firebase.js
export const signInWithGitHub = async () => {
try {
const res = await signInWithPopup(auth, githubProvider);
const user = res.user;
} catch (err) {
throw new Error(err?.message || "Unable to sign in with GitHub");
}
};
Login.jsx
import React, { useEffect, useState } from "react";
import { useAuthState } from "react-firebase-hooks/auth";
import { auth, signInWithGitHub } from "../lib/firebase";
function Login() {
const [user, loading, error] = useAuthState(auth);
const [errorMessage, setErrorMessage] = useState("");
const onLogin = async () => {
try {
await signInWithGitHub();
} catch (err) {
setErrorMessage(err);
}
};
return (
<>
<button onClick={onLogin}>Login with GitHub</button>
{!!errorMessage && <h5>{errorMessage}</h5>}
</>
);
}
I'm trying to set data to my realtime database on firebase. I have used the following code.
I am passing my database name as well as the region in my url still getting this error. Is there anyone who know's what is wrong with the code.
Error "firebase.database(app) arg expects a FirebaseApp instance or undefined.Ensure the arg provided is a Firebase app instance; or no args to use the default Firebase app." I have also initialised the firebase config.
Also I am getting the same problem while fetching data.
import {EMPLOYEE_UPDATE,EMPLOYEE_CREATE,} from './types';
import database from '#react-native-firebase/database';
import auth from '#react-native-firebase/auth';
import { firebase } from '#react-native-firebase/app';
import { Actions } from 'react-native-router-flux';
export const employeeUpdate = ({prop,value}) => {
return {
type: EMPLOYEE_UPDATE,
payload: {prop,value},
};
};
export const employeeCreate = ({name,phone,shift}) => {
const {currentUser} = auth();
return (dispatch) =>{
*const ref = database(
'https://managerproject-8924c-default-rtdb.asia-southeast1.firebasedatabase.app/')
.ref(`/users/${currentUser.uid}/employees`);
console.log(ref);
ref.set({name,phone,shift})
.then(()=> {*
console.log('Data set.');
dispatch({type: EMPLOYEE_CREATE });
Actions.employeeList({type: 'reset'});
});
};
};
As Firebase realtime database documentation,
So, the code will be:
import { firebase } from '#react-native-firebase/database';
firebase
.app()
.database('https://managerproject-8924c-default-rtdb.asia-southeast1.firebasedatabase.app/'))
.ref(`/users/${currentUser.uid}/employees`)
.set({name,phone,shift})
.then(() => console.log('Data set.'))
.catch((error) => console.log(error));
// db.js file
import * as firebase from "firebase/app"
import "firebase/database"
const config = {
apiKey: "" ...
}
const db = firebase.initializeApp(config)
export default db
// App.vue file
import { reactive, onMounted, ref } from 'vue'
import db from "./db.js";
const SendMessage = () => {
const messagesRef = db.database().ref("messages")
if(inputMessage.value === "" || inputMessage.value === null) {
return
}
const message = {
username: state.username,
content: inputMessage.value
}
messagesRef.push(message)
inputMessage.value = ""
}
I try to make a little chat app with Vue.js and Firebase.
So i don't understand because i receive this when i try to send a message :
db_js__WEBPACK_IMPORTED_MODULE_1_.default.database is not a function
at Proxy.SendMessage (App.vue?3dfd:63:1)
I think it's about the import but i try to change for the V9 of firebase but that's didn't work.
Firebase V9 is build in functional aproach. Im working with firestore usually give me a sign if some thing not working.
db.js
import { initializeApp } from 'firebase/app';
import { getDatabase, ref, push, child, serverTimestamp } from 'firebase/database'
const config = {
apiKey: "" ...
}
const firebase = initializeApp(config)
const db = getDatabase()
function addMessage(path, message) {
message.createAt = serverTimestamp() // On database side database will assign current
// timestamp to this field so you will be able to order data
// from newest to oldest for example.
return push(child(ref(db, path)), message)
}
export { addMessage }
App.vue file
import { reactive, onMounted, ref } from 'vue'
import { addMessage } from "./db.js";
const SendMessage = async () => {
if (!inputMessage.value) return
// line above will check are value is "" or null by throwing
// false and using ! in front you changing it to true.
const message = {
username: state.username,
content: inputMessage.value
}
const result = await addMessage('path to data in tree', message)
// async/await will await until data is saved in database and then will do code bellow.
console.log(result.key) // If you await you can read result if result is not void.
inputMessage.value = ""
}
If you use ref() in .vue files make database operations outside of vue files database have same ref() function but they work different. You can allso change name of one function in import line import { ref as dbRef } from 'firebase/database'
I am trying to use Firebase Authentication on my Next.js website. For some reason, when I press the sign up button, nothing happens and no errors are logged. It just refreshes the page. It doesn't even set any cookies or create a user.
Here are my two files related to authentication:
utils/authProvider.js:
import firebase from 'firebase/app';
import 'firebase/auth';
if(!firebase.apps.length) {
firebase.initializeApp({
// config
});
}
const auth = firebase.auth();
module.exports = { auth };
pages/signup.js:
import { useState } from 'react'
import { LockClosedIcon } from '#heroicons/react/solid'
import { auth } from '../utils/authProvider'
export default function CreateAccount() {
const [emailField, setEmailField] = useState('');
const [passwordField, setPasswordField] = useState('');
// emailField and passwordField are set correctly, I used console.log to test it
const createAccount = () => {
// this event does get triggered, I used console.log to test it
auth.createUserWithEmailAndPassword(emailField, passwordField)
.then((userCredential) => {
window.location.replace('/');
console.log('logged in!');
}).catch((error) => {
console.error(error);
});
}
Edit: After experimenting some more, I saw that the request to https://www.googleapis.com/identitytoolkit/v3/relyingparty/signupNewUser never gets completed. It just shows as red in the network traffic tab of Chrome dev tools. Any reason why this might happen?
Thanks in advance.