I have a shoppinglist app that uses Firebase Auth and Realtime DB. I had it working fine before I added the Auth functionality, but now when I login and try to add item or edit, or click anything that is rendered from database the app freezes and I need to close the page and reload, then same thing again.
I can't quite figure out where I went wrong, but the latest changes before the problems started was added to the App.js
:
import React, { useEffect, useState } from 'react'
import './style.css'
import ShopList from './components/shoplist'
import { database, location, auth } from './database/firebase'
import { ref, onValue, update } from 'firebase/database'
import Login from './components/login'
function Firebase() {
const [ data, setData ] = useState([])
const [ gotData, setGotData ] = useState(false)
const [ signedIn, setSignedIn ] = useState()
auth.onAuthStateChanged((user) => {
if (user) {
setSignedIn(true)
} else {
setSignedIn(false)
}
})
useEffect(() => {
const dataRef = ref(database, location)
onValue(dataRef, (snapshot) => {
if (snapshot.exists()) {
setData(snapshot.val())
setGotData(true)
}
})
}, [])
if (signedIn) {
if (gotData) {
const itemDB = Object.entries(data)
return <ShopList data={itemDB} />
} else {
update(ref(database, location), {'':''})
return <div>Loading</div>
}
} else {
return <Login />
}
}
function App() {
return (
<div className="App">
<Firebase />
</div>
);
}
export default App
When I have the code like this it works fine, but then I do not need to login:
import React, { useEffect, useState } from 'react';
import './style.css';
import ShopList from './components/shoplist';
import { database, location } from './database/firebase';
import { ref, onValue, update } from 'firebase/database';
function Firebase() {
const [data, setData] = useState([]);
const [gotData, setGotData] = useState(false);
useEffect(() => {
const dataRef = ref(database, location);
onValue(dataRef, (snapshot) => {
if (snapshot.exists()) {
setData(snapshot.val());
setGotData(true);
}
});
}, []);
if (gotData) {
const itemDB = Object.entries(data)
return <ShopList data={itemDB} />
} else {
update(ref(database, location), {'':''});
return <div>Loading</div>
}
}
function App() {
return (
<div className="App">
<Firebase />
</div>
);
}
export default App
What would be the correct method of checking if the user is authenticated before rendering?
Fairly new to React and Firebase for that matter, so I am sorry in advance if this question is self explanatory for you gurus.