reactjsfirebasereact-nativeexpoasyncstorage

ReactNativeAsyncStorage isn't working as expected on firebase implementation


I'm doing a typical implementation of firebase auth on react native:

// firebaseConfig.ts

import {initializeApp} from 'firebase/app';
import { initializeAuth, getReactNativePersistence } from 'firebase/auth';
import ReactNativeAsyncStorage from '@react-native-async-storage/async-storage';

export const firebaseConfig = {
apiKey:  "XXXXXXXXXX",
authDomain: "XXXXXXXXXX",
projectId:  "XXXXXXXXXX",
storageBucket:  "XXXXXXXXXX",
messagingSenderId: "XXXXXXXXXX",
appId: "XXXXXXXXXX",
measurementId: "XXXXXXXXXX"
};

const app = initializeApp(firebaseConfig);
export const auth = initializeAuth(app, {
persistence: getReactNativePersistence(ReactNativeAsyncStorage)
});

// SessionProvider.tsx

export function SessionProvider(props: PropsWithChildren) {
    const [request, response, promptAsync] = Google.useAuthRequest({
        iosClientId:  '',
        androidClientId: '',
        webClientId: '',
    });

    // Wait for the response of the promptAsync function
    useEffect(() => {
        if (response?.type === 'success') {
            const { id_token } = response.params;
            const credential = GoogleAuthProvider.credential(id_token);
            signInWithCredential(auth, credential);
            router.navigate('/(tabs)');
        }
    }, [response]);

    return (
        <SessionContext.Provider value={{
            signIn: promptAsync,
            signOut: () => signOut(auth),
            session: auth.currentUser?.uid,
            user: auth.currentUser,
            isLoading: !request,
        }}>
            {props.children}
        </SessionContext.Provider>
    );
}

// _layout.tsx

  return (
    <PaperProvider>
      <SessionProvider>
        <Stack
          screenOptions={{
            title: "Vendo mis cosas",
            header: () => <Header />,
          }}
        >
          <Stack.Screen name="(tabs)" />
          <Stack.Screen name="index" />
          <Stack.Screen name="login" />
          <Stack.Screen name="welcome" />
          <Stack.Screen name="signup" />
        </Stack>
      </SessionProvider>
    </PaperProvider>
  );

// index.tsx

const Index = () => {
  const { user } = useSession();

  useEffect(() => {
      console.warn(user, 'index');
  }, [user]);
  
  if (user) {
    return <Redirect href = "/(tabs)"/>;
  }
  return <Redirect href="/welcome" />;
};
export default Index;

I logged-in a user using the gmail registration but when I rebuild the app the console.warn on Index returns null, ReactNativeAsyncStorage isn't persisting the user data, i think it must


Solution

  • I fixed it putting this code

    const app = initializeApp(firebaseConfig);
    export const auth = initializeAuth(app, {
    persistence: getReactNativePersistence(ReactNativeAsyncStorage)
    });
    

    on the _layout.tsx to persist the data