daniel blythe
daniel blythe

Reputation: 1048

How to use asyncWithLDProvider from Launch Darkly with Next app

Launch Darkly have an example(https://github.com/launchdarkly/react-client-sdk/blob/main/examples/async-provider/src/client/index.js) of how to use asyncWithLDProvider with a React project (as below) but I cannot figure out how to integrate this with my Next app.

Example

import { asyncWithLDProvider } from 'launchdarkly-react-client-sdk';

(async () => {
  const LDProvider = await asyncWithLDProvider({
    clientSideID: 'client-side-id-123abc',
    user: {
      "key": "user-key-123abc",
      "name": "Sandy Smith",
      "email": "[email protected]"
    },
    options: { /* ... */ }
  });

  render(
    <LDProvider>
      <YourApp />
    </LDProvider>,
    document.getElementById('reactDiv'),
  );
})();

Have tried creating a provider in the _app.tsx file and wrapping the entire app but as asyncWithLDProvider is async and requires the await keyword this is tricky.

Something like this

const App = ({ Component }) = {
    // but how to get this async function to work with the React lifecycle stumps me
    const LDProvider = await asyncWithLDProvider({
      clientSideID: 'client-side-id-123abc',
    });

    return (
        <LDProvider>
            <Component />
        </LDProvider>
    )
}

Here is my _app.tsx (have removed a few imports to save space)

This is a group project and not all of this was written by me.

import { Next, Page } from '@my/types';
import NextHead from 'next/head';
import { QueryClient, QueryClientProvider } from 'react-query';

const App = ({
  Component,
  pageProps: { session, ...restProps },
}: Next.AppPropsWithLayout) => {
  const { pathname } = useRouter();
  const { description, title } = Page.getMetadata(pathname, ROUTES);

  const getLayout = Component.getLayout ?? ((page) => page);
  const WithRedirectShell = withRedirect(Shell);

  const queryClient = new QueryClient();

  const [colorScheme, setColorScheme] = useLocalStorage<ColorScheme>({
    key: 'mantine-color-scheme',
    defaultValue: 'light',
    getInitialValueInEffect: true,
  });

  const toggleColorScheme = (value?: ColorScheme) =>
    setColorScheme(value || (colorScheme === 'dark' ? 'light' : 'dark'));

  useHotkeys([['mod+J', () => toggleColorScheme()]]);

  return (
    <ColorSchemeProvider
      colorScheme={colorScheme}
      toggleColorScheme={toggleColorScheme}
    >
      <MantineProvider
        withGlobalStyles
        withNormalizeCSS
        theme={{ colorScheme, ...theme }}
      >
        <NotificationsProvider position='top-center' zIndex={2077} limit={5}>
          <SessionProvider session={session}>
            <QueryClientProvider client={queryClient}>
              <NextHead>
                <Head description={description} title={title} />
              </NextHead>
              <WithRedirectShell header={<Header />}>
                {getLayout(<Component {...restProps} />)}
              </WithRedirectShell>
            </QueryClientProvider>
          </SessionProvider>
        </NotificationsProvider>
      </MantineProvider>
    </ColorSchemeProvider>
  );
};

export default App;

Here is my index.tsx

import { Next } from "@my/types";

const Home: Next.Page = () => null;

export default Home;

Upvotes: 11

Views: 1851

Answers (1)

Murphpdx
Murphpdx

Reputation: 122

The launchdarkly-react-client-sdk also exports a component called LDProvider. You can just import that and pass in your context.

Using app routing, you can create a Provider component and pass in your user context. At the top of this file, add 'use client' to make it a client component. Then, you can import this component into your root layout. The layout component will remain a server component, and if the children are server components, they will remain server components.

'use client';

import React from 'react';
import { LDProvider } from 'launchdarkly-react-client-sdk';

export const Providers = ({ children, user }: Props) => {
  const LDContext = {
    kind: 'user',
    key: 'user key here',
  };

  return (
    <LDProvider
      context={LDContext}
      clientSideID="YOUR KEY HERE"
    >
      {children} 
    </LDProvider>
  );
}

There is also a sample app using page routing: https://github.com/tanben/sample-nextjs

Upvotes: 2

Related Questions