Я новичок в реагировании и пожарной базе и пытаюсь создать систему аутентификации. Тем не менее, мой проект дает мне ошибку в authcontext.tsx: < /p>
не может прочитать авторитет. Автор не готов при использовании наблюдателя OnauthstateChanged, ошибка использования. Я попытался добавить загрузку или auth в массив зависимостей от использования, все еще не работает.// Import the functions you need from the SDKs you need
import { initializeApp } from "@firebase/app";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/se ... -libraries
import { initializeAuth, getReactNativePersistence, getAuth } from "@firebase/auth";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { getFirestore } from "@firebase/firestore";
import firebase from "firebase/compat/app";
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "apikey",
authDomain: "eample.firebaseapp.com",
projectId: "exampleId",
storageBucket: "example.firebasestorage.app",
messagingSenderId: "id",
appId: "appid"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
console.log('it is called');
const auth = initializeAuth(app,{
persistence : getReactNativePersistence(AsyncStorage)
})
const firestore = getFirestore(app);
export {app, auth, firestore}
< /code>
authcontext.tsx
< /blockquote>
import { createContext, useContext, useEffect, useState } from "react";
import { AuthContextType, UserType } from "../types";
import { signInWithEmailAndPassword } from "firebase/auth/cordova";
import { auth,firestore } from "../config/firebase";
import { onAuthStateChanged } from "@firebase/auth";
import { useNavigation } from "@react-navigation/native";
import { Text } from "react-native";
const AuthContext = createContext(null);
export const AuthProvider:React.FC = ({children}) => {
const [user,setUser] = useState(null);
const [loading, setLoading] = useState(true);
//const navigation:any = useNavigation();
useEffect(()=>{
const unsub = onAuthStateChanged(auth,(firebaseUser)=> {
console.log('firebase User',firebaseUser);
setLoading(false);
})
return () => unsub();
},[]);
const login = async (email:string,password:string) => {
try {
await signInWithEmailAndPassword(auth,email,password);
return {success:true}
}
catch(error:any){
let msg = error.message;
return {success:false,msg}
}
}
const contextValue:AuthContextType = {
user,
setUser,
login,
};
if (loading) {
return Loading...; // Or a loading spinner
}
return (
{!loading && children}
);
}
export const useAuth = ():AuthContextType => {
const context = useContext(AuthContext);
if(!context) {
throw new Error("useAuth must be wrapped inside AuthProvider");
}
return context;
}
< /code>
App.tsx
< /blockquote>
import React from 'react';
import './gesture-handler';
import { Text, View } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import StackNavigator from './navigation/StackNavigation';
import { AuthProvider } from './context/AuthContext';
function App() {
return (
);
}
export default App;
Подробнее здесь: https://stackoverflow.com/questions/796 ... uthcontext
Как инициализировать Firebase и ее AUTH перед использованием крючка AuthContext? ⇐ Javascript
Форум по Javascript
1746139478
Anonymous
Я новичок в реагировании и пожарной базе и пытаюсь создать систему аутентификации. Тем не менее, мой проект дает мне ошибку в authcontext.tsx: < /p>
не может прочитать авторитет. Автор не готов при использовании наблюдателя OnauthstateChanged, ошибка использования. Я попытался добавить загрузку или auth в массив зависимостей от использования, все еще не работает.// Import the functions you need from the SDKs you need
import { initializeApp } from "@firebase/app";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
import { initializeAuth, getReactNativePersistence, getAuth } from "@firebase/auth";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { getFirestore } from "@firebase/firestore";
import firebase from "firebase/compat/app";
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "apikey",
authDomain: "eample.firebaseapp.com",
projectId: "exampleId",
storageBucket: "example.firebasestorage.app",
messagingSenderId: "id",
appId: "appid"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
console.log('it is called');
const auth = initializeAuth(app,{
persistence : getReactNativePersistence(AsyncStorage)
})
const firestore = getFirestore(app);
export {app, auth, firestore}
< /code>
[b] authcontext.tsx[/b]
< /blockquote>
import { createContext, useContext, useEffect, useState } from "react";
import { AuthContextType, UserType } from "../types";
import { signInWithEmailAndPassword } from "firebase/auth/cordova";
import { auth,firestore } from "../config/firebase";
import { onAuthStateChanged } from "@firebase/auth";
import { useNavigation } from "@react-navigation/native";
import { Text } from "react-native";
const AuthContext = createContext(null);
export const AuthProvider:React.FC = ({children}) => {
const [user,setUser] = useState(null);
const [loading, setLoading] = useState(true);
//const navigation:any = useNavigation();
useEffect(()=>{
const unsub = onAuthStateChanged(auth,(firebaseUser)=> {
console.log('firebase User',firebaseUser);
setLoading(false);
})
return () => unsub();
},[]);
const login = async (email:string,password:string) => {
try {
await signInWithEmailAndPassword(auth,email,password);
return {success:true}
}
catch(error:any){
let msg = error.message;
return {success:false,msg}
}
}
const contextValue:AuthContextType = {
user,
setUser,
login,
};
if (loading) {
return Loading...; // Or a loading spinner
}
return (
{!loading && children}
);
}
export const useAuth = ():AuthContextType => {
const context = useContext(AuthContext);
if(!context) {
throw new Error("useAuth must be wrapped inside AuthProvider");
}
return context;
}
< /code>
[b] App.tsx[/b]
< /blockquote>
import React from 'react';
import './gesture-handler';
import { Text, View } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import StackNavigator from './navigation/StackNavigation';
import { AuthProvider } from './context/AuthContext';
function App() {
return (
);
}
export default App;
Подробнее здесь: [url]https://stackoverflow.com/questions/79602625/how-to-initialize-firebase-and-its-auth-before-useeffect-hook-of-authcontext[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия