I have implemented firebase authentication (login and register with email) in my React app, but now I want to upgrade with remember me checkbox. I'm familiar with onAuthStateChanged listener, and partially I know how it works. In last app I used Context(onAuthStaeChanged was in Context), but now I'm not using it and I'm trying to figure out where is best place to set that listener.
Also for remember me checkbox I'm trying to find some documentation on firebase and didn't manage to find anything except setPersistence .. but they didn't really explained it well, atleast not for me :P. I guess that default persistence is local so it should be set when checkbox is checked, and session when checkbox is unchecked.
So if any1 have any expirience with this, my question is where is best place to set useEffect with onAuthStateChanged and how to implement checkbox remember be, because user is always staying logged in by default?
I'm not providing any code since It's really basic code from firebase authentication.I have Login, Register and Home component. But in case someone need to see my code to help me I will edit post with code sample. Thanks!
I managed to do it in this very simple way:
import { browserSessionPersistence, setPersistence } from "firebase/auth";
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
if (!authPersistence) {
setPersistence(auth, browserSessionPersistence);
}
signInWithEmailAndPassword(authForm.email, authForm.password);
};
Checkbox html:
<label>
<input
type="checkbox"
onClick={(e) => setAuthPersistence(!authPersistence)}
/>
Remember me
</label>
So if user check checkbox state changed to true and setPersistence will not be triggered. BrowserSessionPersistence is that if user close tab or browser he will be logged out, and I think that browsetSessionLocal is default value, but in this case I don't have to deal with it :). Edit: On refresh or loading another component user is not logged off.