Last active
November 4, 2021 16:21
-
-
Save amcclosky/054d73765d698fdabea7efafbdb8f495 to your computer and use it in GitHub Desktop.
useCommandBar - React Hook for 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
// 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 |
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
// 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