-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add page testing out context provider with atoms
- Loading branch information
1 parent
1edf0d8
commit 1fa4a99
Showing
1 changed file
with
59 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
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> | ||
) | ||
} |
1fa4a99
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Successfully deployed to the following URLs:
games – ./apps/games
games.emiljohansson.dev
games-emiljohansson.vercel.app
games-git-main-emiljohansson.vercel.app
games-ivory.vercel.app