bnexd
bnexd

Reputation: 161

React with Firebase Auth: How to set Persistence?

I'm running into an error with my Login:

const Login = ({ history }) => {
const handleLogin = useCallback(
    async event => {
        event.preventDefault();
        const { email, password } = event.target.elements;
        try {
            await app
                .auth()
                .signInWithEmailAndPassword(email.value, password.value);
            app.auth().setPersistence(app.auth.Auth.Persistence.SESSION);
            history.push("/feed");
        } catch (error) {
            alert(error);
        }
    },
    [history]
);

I think that my setPersistence is at the wrong place but I don't know how to fix that. My import list:

import React, { useCallback, useContext } from "react";
import { withRouter, Redirect } from "react-router";
import app from "../../firebase";
import { AuthContext } from "../../Auth";

Thank you!

Upvotes: 1

Views: 6884

Answers (1)

Arsen Ghazaryan
Arsen Ghazaryan

Reputation: 1050

You have to call setPersistence before calling signInWithEmailAndPassword.

const Login = ({ history }) => {
const handleLogin = useCallback(
    async event => {
        event.preventDefault();
        const { email, password } = event.target.elements;
        try {
            await app.auth().setPersistence(app.auth.Auth.Persistence.SESSION);
            await app
                .auth()
                .signInWithEmailAndPassword(email.value, password.value);
            history.push("/feed");
        } catch (error) {
            alert(error);
        }
    },
    [history]
);

Upvotes: 4

Related Questions