Last active
May 1, 2021 11:56
-
-
Save Dchole/82cc90a2cd96da5696160dc059562230 to your computer and use it in GitHub Desktop.
Store user's device or platform in React Context API
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
// Context API for device | |
import { createContext, useEffect, useState } from "react"; | |
export type TDevice = "mobile" | "desktop"; | |
export const DeviceContext = createContext<TDevice>("mobile"); | |
const DeviceContextProvider: React.FC = ({ children }) => { | |
const [device, setDevice] = useState<TDevice>("mobile"); | |
useEffect(() => { | |
const { userAgent } = navigator; | |
// Set device state | |
userAgent.includes("Mobi") ? setDevice("mobile") : setDevice("desktop"); | |
}, []); | |
return ( | |
<DeviceContext.Provider value={device}>{children}</DeviceContext.Provider> | |
); | |
}; | |
export default DeviceContextProvider; |
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
// login with provider hook | |
const useLoginWithProvider = (redirect: (path: string) => void) => { | |
const device = useContext(DeviceContext); | |
const [signInAttempt, setSignInAttempt] = useState(false); | |
const login = async (provider: string) => { | |
if (device === "mobile") { // Check if user is mobile | |
firebase.auth().signInWithRedirect(providers[provider]); | |
setSignInAttempt(true); | |
} else { | |
firebase | |
.auth() | |
.signInWithPopup(providers[provider]) | |
.then(handleResult) | |
.catch(error => setError(error.message)); | |
} | |
}; | |
useEffect(() => { | |
if (signInAttempt) { | |
firebase | |
.auth() | |
.getRedirectResult() | |
.then(handleResult) | |
.catch(error => setError(error.message)); | |
} | |
}, []); | |
return login; | |
}; | |
export default useLoginWithProvider; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment