onUserChanged always triggered
luismartinezs opened this issue · comments
I'm not sure I understand when this function is supposed to trigger, but a simple route navigation out and in the same page will run this function, even if the user didn't change.
For example:
const LoginPage = () => {
const [authUser] = useAuthState(useAuth(), {
onUserChanged: async (user) => {
// this will always run, even if the user didn't change
if (user) {
await userDataAPI.initUserData(user); // I only want to run this if the user exists and changed
}
},
});
// render logic
So I had to store the user as a variable and compare it with the new one, like so:
let prevUser: User | null = null;
const LoginPage = () => {
const [authUser] = useAuthState(useAuth(), {
onUserChanged: async (user) => {
if (user && prevUser !== user) {
await userDataAPI.initUserData(user); // now this will run only if the user is different
prevUser = user;
}
},
});
// render logic
Am I simply misunderstanding how onUserChanged
is supposed to work?
@luismartinezs Apologies for the delayed response. useAuthState
will run every time that a component is mounted, so it is correctly running when you navigate away and back to the page.
Typically you would use useAuthState
at the root of your application rather than within a particular route to ensure that it is only ever run once.
yeah..im so confuse. in my case im having sidebar that i hide/move to leftside (still 1 screen component), when i pull and cancel open the sidebar, the data always retrigger and reloading. and when im try just change useState hook also reloading..even nothing todo with firebase.
but when i try to change value on firebase web console, my app can receive the value without reload element at all.
any advice how to solve this behaviour?
Your hook needs to be places above all the other code in your application
function App() {
useAuthState();
<Layout>
<Sidebar />
<Page />
</Layout>
}