'keep user logged in while using supabase in react native

I built an auth function that looks like this:

const handleLogin = async (type) => {
    const { user, error } =
      type === "LOGIN"
        ? await supabase.auth.signIn({ email, password })
        : await supabase.auth.signUp({ email, password });

    if (error) {
      alert(error);
    } else if (!user && !error) {
      alert("An email has been sent to you for verification!");
    }
  };

Fetching the jwt and getting the user:

   useEffect(() => {
    
        async () => {
          const jwt = await AsyncStorage.getItem("user");
          const currentUser = supabase.auth.api.getUser(jwt)
          console.log(currentUser)
        }
    
    
        const session = supabase.auth.session();
        setUser(session?.user ?? null);
    
        const { data: authListener } = supabase.auth.onAuthStateChange(
          async (event, session) => {
            const currentUser = session?.user;
            await AsyncStorage.setItem("user", session.access_token);
            console.log(await AsyncStorage.getItem("user"));
            setUser(currentUser ?? null);
          }
        );
    
        return () => {
          authListener?.unsubscribe();
        };
      }, [user]);

but I can't seem to find a way to keep the user logged in inside the app. everytime it restarts the user needs to login again.

Any ideas? Thanks in advance!



Solution 1:[1]

but I can't seem to find a way to keep the user logged in inside the app. everytime it restarts the user needs to login again.

The JS library should already be detecting the user session from the AsyncStorage and restoring it automatically. You can see this logic inside the Auth lib:

Call from constructor: https://github.com/supabase/gotrue-js/blob/8d7eef85a41c5e94a1336f0f44eacc5253186e9b/src/GoTrueClient.ts#L106-L107

Which calls this function: https://github.com/supabase/gotrue-js/blob/8d7eef85a41c5e94a1336f0f44eacc5253186e9b/src/GoTrueClient.ts#L637

You should be able to just add a listener (supabase.auth.onAuthStateChange()) and it will get triggered once the library has refreshed the session. You can add the listener in a useEffect (like you do above), but without the [user] argument so that it is set up immediately.

Solution 2:[2]

You can use the following method to acheive this.

  1. Use AsyncStorage to store token locally.
  2. in UseEffect of App.js get token from AsyncStorage if user receives the token then navigate app to your Home Screen.
  3. if token is not received navigate app to login Screen.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 kiwicopple
Solution 2 DharmanBot