Firebase, React Native: database connected but can't fetch data from firestore
I am working on a simple React Native app and need to connect to the database (in this case firebase firestore). I've tried few packages but the problem is still there. Currently I'm using firebase ^9.6.3 (modular version) > (by 'npm install --save firebase').
initialized firebase...
import {initializeApp} from 'firebase/app';
import {getFirestore} from 'firebase/firestore';
const firebaseConfig = {
...
};
const app = initializeApp(firebaseConfig);
export const db = getFirestore(app);
tried to get data..
const Firestore = () => {
const [state, setstate] = useState('');
const getData = async database => {
try {
const user = doc(database, 'testData', 'testDoc');
const userSnap = await getDoc(user);
const userName = userSnap.data().name;
setstate(userName);
return state;
} catch (error) {
alert(error.message);
}
};
{
useEffect(() => {
getData(db);
}, []);
}
return (
<View>
<Text>not showing... {state}</Text>
</View>
);
};
export default Firestore;
Though the code is fine and firebase dashboard shows the device is connected but data can't be fetched. The alerts shows: 'Failed to get document because the client is offline.' though the internet connection is okay and I can fetch data/files from other sources. I need help..
Solution 1:
Can you try this:
const Firestore = () => {
const [state, setstate] = useState('');
useEffect(() => {
async function getData(database){
try {
const user = doc(database, 'testData', 'testDoc');
const userSnap = await getDoc(user);
const userName = userSnap.data().name;
setstate(userName);
return state;
} catch (error) {
alert(error.message);
}
}
getData(db);
},[])
return (
<View>
<Text>not showing... {state}</Text>
</View>
);
};
export default Firestore;