|
| 1 | +import { GetServerSideProps, InferGetServerSidePropsType } from 'next' |
| 2 | +import Head from 'next/head' |
| 3 | +import Image from 'next/image' |
| 4 | +import styles from '../styles/Home.module.css' |
| 5 | +import { atom, useAtom } from 'jotai' |
| 6 | +import { useAtomValue, useHydrateAtoms } from 'jotai/utils' |
| 7 | + |
| 8 | +const countAtom = atom(0) |
| 9 | +const doubleAtom = atom((get) => get(countAtom) * 2) |
| 10 | + |
| 11 | +export const getServerSideProps: GetServerSideProps<{ |
| 12 | + initialCount: number |
| 13 | +}> = async (context) => { |
| 14 | + return { props: { initialCount: 42 } } |
| 15 | +} |
| 16 | + |
| 17 | +export default function Home({ |
| 18 | + initialCount, |
| 19 | +}: InferGetServerSidePropsType<typeof getServerSideProps>) { |
| 20 | + useHydrateAtoms([[countAtom, initialCount]] as const) |
| 21 | + const [count, setCount] = useAtom(countAtom) |
| 22 | + const doubleCount = useAtomValue(doubleAtom) |
| 23 | + return ( |
| 24 | + <div className={styles.container}> |
| 25 | + <Head> |
| 26 | + <title>with-jotai</title> |
| 27 | + <meta name="description" content="Generated by create next app" /> |
| 28 | + <link rel="icon" href="/favicon.ico" /> |
| 29 | + </Head> |
| 30 | + <h1 className={styles.title}>With Jotai example</h1> |
| 31 | + <main className={styles.main}> |
| 32 | + <div>Initial count from the server: {count}</div> |
| 33 | + <div>Double count: {doubleCount}</div> |
| 34 | + <button onClick={() => setCount((count) => count + 1)}>+1</button> |
| 35 | + </main> |
| 36 | + <footer className={styles.footer}> |
| 37 | + <a |
| 38 | + href="https://vercel.com?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app" |
| 39 | + target="_blank" |
| 40 | + rel="noopener noreferrer" |
| 41 | + > |
| 42 | + Powered by{' '} |
| 43 | + <span className={styles.logo}> |
| 44 | + <Image src="/vercel.svg" alt="Vercel Logo" width={72} height={16} /> |
| 45 | + </span> |
| 46 | + </a> |
| 47 | + </footer> |
| 48 | + </div> |
| 49 | + ) |
| 50 | +} |
0 commit comments