Skip to content

Instantly share code, notes, and snippets.

@hideokamoto
Created May 12, 2022 08:20
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 hideokamoto/f4fabf01ae1a50708dba0dc398c96226 to your computer and use it in GitHub Desktop.
Save hideokamoto/f4fabf01ae1a50708dba0dc398c96226 to your computer and use it in GitHub Desktop.
LIFF with Next.js
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
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
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