Created
May 12, 2022 08:20
-
-
Save hideokamoto/f4fabf01ae1a50708dba0dc398c96226 to your computer and use it in GitHub Desktop.
LIFF with Next.js
This file contains hidden or 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
import type { AppProps } from 'next/app' | |
import { LiffProvider } from './LiffProvider' | |
function MyApp({ Component, pageProps }: AppProps) { | |
return ( | |
<LiffProvider liffId={process.env.NEXT_PUBLIC_LIFF_ID as string}> | |
<Component {...pageProps} /> | |
</LiffProvider> | |
) | |
} | |
export default MyApp |
This file contains hidden or 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
import type { NextPage } from 'next' | |
import Head from 'next/head' | |
import { useEffect } from 'react' | |
import { useLiff } from './LiffProvider' | |
const Home: NextPage = () => { | |
const { liff } = useLiff() | |
useEffect(() => { | |
if (!liff) return; | |
if (!liff.isLoggedIn()) { | |
return liff.login() | |
} | |
liff.getProfile() | |
.then(profile => { | |
console.log(profile) | |
}) | |
},[liff]) | |
return ( | |
<div> | |
<Head> | |
<title>hello</title> | |
</Head> | |
<main> | |
<h1>Hello liff</h1> | |
</main> | |
</div> | |
) | |
} | |
export default Home |
This file contains hidden or 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
import { createContext, FC, PropsWithChildren, useContext, useEffect, useRef, useState } from "react"; | |
import { Liff } from '@line/liff' | |
const LiffContext = createContext<{ | |
liff?: Liff | |
}>({}) | |
export const useLiff = () => useContext(LiffContext) | |
export const LiffProvider: FC<PropsWithChildren<{ | |
liffId: string; | |
}>> = ({children, liffId}) => { | |
const didLoadRef = useRef(false) | |
const [liff, setLiff] = useState<Liff | undefined>() | |
useEffect(() => { | |
if (typeof window === 'undefined') return; | |
if (didLoadRef.current === true) return; | |
didLoadRef.current = true | |
import('@line/liff') | |
.then(async (data: any) => { | |
await data.init({ | |
liffId | |
}) | |
setLiff(data) | |
}) | |
}, [liffId]) | |
return ( | |
<LiffContext.Provider | |
value={{ | |
liff, | |
}} | |
> | |
{children} | |
</LiffContext.Provider> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment