1

In my react-native app, I am trying to keep my user logged in by using the persist middleware in my zustand store but it doesnt seem to work, I do call the right methods declared in my store in my different screens (LoginScreen, LogoutScreen) but it doesnt seem to work, here is my authentification Store :

import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';
import { auth } from '../firebase';
import { signInWithEmailAndPassword, onAuthStateChanged } from 'firebase/auth';
import AsyncStorage from '@react-native-async-storage/async-storage';

const useAuthStore = create(
  persist(
    (set) => ({
      user: null,

      checkAuthState: () => {
        return onAuthStateChanged(auth, (user) => {
          if (user) {
            set({ user });
            console.log("CheckAuth user:", user.email);
          } else {
            set({ user: null });
            console.log("CheckAuth user: null");
          }
        });
      },

      login: async (email, password) => {
        try {
          const userCredential = await signInWithEmailAndPassword(auth, email, password);
          const user = userCredential.user;
          set({ user });
          return user;
        } catch (error) {
          console.log('Error: ', error);
          throw error;
        }
      },

      logout: async () => {
        try {
          await auth.signOut();
          set({ user: null });
        } catch (error) {
          console.log('Error: ', error);
          throw error;
        }
      },
    }),
    {
      name: "user-state",
      storage: createJSONStorage(() => AsyncStorage),
    }
  )
);

export default useAuthStore;

I also know that asyncStorage is indeed keeping my user thanks to this function in my mainScreen once logged in :

// Function to log the persisted data in AsyncStorage
const logPersistedData = async () => {
  try {
    const data = await AsyncStorage.getItem('user-state');
    console.log('Persisted Data:', data);
  } catch (error) {
    console.log('Error retrieving persisted data:', error);
  }
};

// Call the function to log the persisted data
logPersistedData();

So here I am, no error shown, trying to figure out why am I not still logged in when i refresh the app.

Also, I am using expo to serve my app on my phone, maybe it has something to do with my problem ?

Guigz
  • 41
  • 1

0 Answers0