Skip to content

Instantly share code, notes, and snippets.

@Dchole
Last active May 1, 2021 11:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Dchole/82cc90a2cd96da5696160dc059562230 to your computer and use it in GitHub Desktop.
Save Dchole/82cc90a2cd96da5696160dc059562230 to your computer and use it in GitHub Desktop.
Store user's device or platform in React Context API
// 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;
// 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