Skip to content

Commit

Permalink
add page testing out context provider with atoms
Browse files Browse the repository at this point in the history
  • Loading branch information
emiljohansson committed Jan 21, 2024
1 parent 1edf0d8 commit 1fa4a99
Showing 1 changed file with 59 additions and 0 deletions.
59 changes: 59 additions & 0 deletions apps/next/src/app/state-management/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
'use client'

import { createContext, useContext as useReactContext } from 'react'
import { atom, WritableAtom } from 'nanostores'
import { useStore } from '@nanostores/react'

export const NanoContext = createContext<WritableAtom>({} as WritableAtom)
function NanoProvider<T>({
children,
store,
}: {
children: React.ReactNode
store: WritableAtom<T>
}) {
return <NanoContext.Provider value={store}>{children}</NanoContext.Provider>
}
export function useContext() {
const atom = useReactContext(NanoContext)
if (!atom) throw new Error('No store')
const store = useStore(atom!)

return [
store,
(newValue: unknown) => {
atom.set(newValue)
},
atom,
]
}

function Count() {
const [count, setCount] = useContext()

return (
<button
onClick={() => {
setCount(count + 1)
}}
>
{count}
</button>
)
}

export default function Page() {
return (
<div>
<NanoProvider store={atom(0)}>
<Count />
<Count />
</NanoProvider>
<hr />
<NanoProvider store={atom(0)}>
<Count />
<Count />
</NanoProvider>
</div>
)
}

1 comment on commit 1fa4a99

@vercel
Copy link

@vercel vercel bot commented on 1fa4a99 Jan 21, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.