ReactNativeAsyncStorage 在 Firebase 实现中未按预期工作

问题描述 投票:0回答:1

我正在 React Native 上进行 Firebase 身份验证的典型实现:

// 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;

我使用 gmail 注册登录了用户,但是当我重建应用程序时,索引上的 console.warn 返回 null,ReactNativeAsyncStorage 不会保留用户数据,我认为它必须

reactjs firebase react-native expo asyncstorage
1个回答
0
投票

我修复了它并放置了这段代码

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

_layout.tsx
上保存数据

© www.soinside.com 2019 - 2024. All rights reserved.