Skip to content

Instantly share code, notes, and snippets.

@amcclosky
Last active November 4, 2021 16:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amcclosky/054d73765d698fdabea7efafbdb8f495 to your computer and use it in GitHub Desktop.
Save amcclosky/054d73765d698fdabea7efafbdb8f495 to your computer and use it in GitHub Desktop.
useCommandBar - React Hook for next.js
// yarn add commandbar or npm install commandbar --save
import { useEffect } from 'react'
import { init as initCommandBar } from 'commandbar'
const COMMANDBAR_ORG =
process.env.COMMANDBAR_ORG || process.env.NEXT_PUBLIC_COMMANDBAR_ORG
function useCommandBar({ org = COMMANDBAR_ORG, userId, userMeta = {} }) {
const _CommandBar = typeof window !== 'undefined' ? window.CommandBar : null
useEffect(() => {
// if CommandBar doesn't exist yet then run init
if (!!_CommandBar) return
initCommandBar(org)
}, [_CommandBar, org])
useEffect(() => {
// once we have both a userId and CommandBar then boot
if (!userId || !_CommandBar) return
_CommandBar.boot(userId, userMeta)
}, [userId, _CommandBar])
return _CommandBar
}
export default useCommandBar
// possible usage of useCommandBar
// note: this snippet is just an example and isn't actually tested.
// the hook itself works within a full app
import 'styles/globals.css'
import { Provider, useSession } from 'next-auth/client'
import useCommandBar from 'hooks/command-bar'
function Layout({ children }) {
const [session] = useSession()
const {.user } = session
const userId = user?.id
useCommandBar({userId})
return <div>{{ children }}</div>
}
function App({ Component, pageProps }) {
return (
<>
<Provider session={pageProps.session}>
<Layout>
<Component {...pageProps} />
</Layout>
</Provider>
</>
)
}
export default App
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment