-
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
0e09049
commit 2ed7a52
Showing
2 changed files
with
10 additions
and
28 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,26 +1,26 @@ | ||
import type { FirebaseAuthTypes } from '@react-native-firebase/auth' | ||
import auth from '@react-native-firebase/auth' | ||
import { useEffect, useState } from 'react' | ||
import { useEffect, useRef } from 'react' | ||
|
||
/** | ||
* Recoilが使えない環境の時にもユーザーを持ちたい場合に使います。基本的に `useCachedAnonymousUser` を使ってください。 | ||
*/ | ||
const useAnonymousUser = (): FirebaseAuthTypes.User | undefined => { | ||
const [user, setUser] = useState<FirebaseAuthTypes.User>() | ||
const userRef = useRef<FirebaseAuthTypes.User>() | ||
useEffect(() => { | ||
const unsubscribe = auth().onAuthStateChanged((authUser) => { | ||
if (authUser) { | ||
setUser(authUser) | ||
userRef.current = authUser | ||
} else { | ||
auth() | ||
.signInAnonymously() | ||
.then((credential) => setUser(credential.user)) | ||
.then((credential) => (userRef.current = credential.user)) | ||
} | ||
}) | ||
return unsubscribe | ||
}, [setUser, user]) | ||
}, []) | ||
|
||
return user | ||
return userRef.current | ||
} | ||
|
||
export default useAnonymousUser |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters