2.0.0-beta.9 • Published 2 years ago

nextjs-storage v2.0.0-beta.9

Weekly downloads
-
License
Apache-2.0
Repository
github
Last release
2 years ago

Next.js Storage

A storage system optimized for nextjs

Features:

  • No Flashing/Popping
  • Super-Reactive, update all states that uses the same name
  • Repository based, you can provide your own data
  • Supports Cookies 😋

Caveats:

  • Can't be used outside react
  • Needs getInitialProps to work as promised

How to use

// For Next.js only:
App.getInitialProps = async (context) => {
    const initialProps = await App.getInitialProps(context);

    return {
        ...initialProps,
        cookies: context.ctx.req?.headers?.cookie
    };
};

function App({cookies}) {
    /* Note that you manually pass the cookies string! */
    const cookieRepository = useCookieRepositoryState(cookies)
    const storage = useStorageState({
        repositories: [cookieRepository],
        options: {
            repository: "cookie"
        }
    })

    return (
        <StorageProvider storage={storage}>
            <ABasicComponent />
            <AnAdvancedComponent />
        </StorageProvider>
    )
}

function ABasicComponent() {
    const [cookie, setCookie] = useCookie("my-cookie")

    return <>
        <input
            value={cookie}
            onChange={e => setCookie(e.target.value)}
        />
    </>
}

function AnAdvancedComponent() {
    const storage = useStorage()

    return <>
        <button onClick={() => {
            storage.setItem("my-cookie", "my value", {
                repository: "cookie",
                attributes: {
                    maxAge: 10
                }
            })
        }} />
    </>
}