I'm building a ReactJS project and I'm using something like this, to provide user data trough the app:
function Comp1() {
const [user, setUser] = useState({});
firebase.auth().onAuthStateChanged(function (_user) {
if (_user) {
// User is signed in.
// do some firestroe queryes to get all the user's data
setUser(_user);
} else {
setUser({ exists: false });
}
});
return (
<div>
<UserProvider.Provider value=>
<Comp2 />
<Comp3 />
</UserProvider.Provider>
</div>
);
}
function Comp2(props) {
const { user, setUser } = useContext(UserProvider);
return (
<div>
{user.exists}
</div>
)
}
function Comp3(props) {
const { user, setUser } = useContext(UserProvider);
return (
<div>
{user.exists}
</div>
)
}
//User Provider
import React from 'react';
const UserProvider = React.createContext();
export default UserProvider;
So, in this case, Comp1 provides user data to Comp2 & Comp3. The only problem is that when the user state changes or the page loads, it creates an infinite loop. If I'm not using an useState for storing the user data, then when it changes, the components do not get re-rendered. I also tried to do something like this in the index.js file:
firebase.auth().onAuthStateChanged(function (user) {
if (user) {
ReactDOM.render(<Comp1 user={user} />, document.getElementById('root'));
} else {
ReactDOM.render(<Comp1 user= />, document.getElementById('root'));
}
});
But this worked a bit weirdly sometimes, and it's kinda messy. What solutions are there? Thanks.
Edit: I'm triening to do it in the wrong way? How should I provide all user data with only one firebase query?
from How to treat global user/user data in react?
No comments:
Post a Comment