From 9ed33beca0850aedb7fa6899efc45fb50a16531f Mon Sep 17 00:00:00 2001 From: Kohei Watanabe Date: Sun, 9 Feb 2020 05:53:07 +0900 Subject: [PATCH] add todo list sample --- next-env.d.ts | 3 +- pages/index.md | 3 ++ pages/todo.tsx | 78 ++++++++++++++++++++++++++++++++++++++++++++++++++ tsconfig.json | 3 +- 4 files changed, 85 insertions(+), 2 deletions(-) create mode 100644 pages/todo.tsx diff --git a/next-env.d.ts b/next-env.d.ts index c9a6f33..9739e18 100644 --- a/next-env.d.ts +++ b/next-env.d.ts @@ -1,7 +1,8 @@ /// /// declare module "@mdx-js/react" { - let MDXProvider: React.FC<{ + const MDXContext: React.Context; + const MDXProvider: React.FC<{ components: any; childlen?: ReactNode; }>; diff --git a/pages/index.md b/pages/index.md index 3204983..aa440c6 100644 --- a/pages/index.md +++ b/pages/index.md @@ -1,3 +1,6 @@ +import Todo from "./todo" + # Hello Next.js - [About](/about) +- [ToDo List](/todo) diff --git a/pages/todo.tsx b/pages/todo.tsx new file mode 100644 index 0000000..87b72a3 --- /dev/null +++ b/pages/todo.tsx @@ -0,0 +1,78 @@ +import React, { FormEvent } from "react"; +import { MDXContext } from "@mdx-js/react"; + +type State = { + id: number; + todo: Map; +}; +type Action = + | { + type: "add"; + body: string; + } + | { + type: "delete"; + key: number; + }; + +const initialState: State = { + id: 0, + todo: new Map() +}; + +function reducer(state: State, action: Action) { + switch (action.type) { + case "add": + state.todo.set(state.id, action.body); + return { ...state, id: state.id + 1 }; + case "delete": + state.todo.delete(action.key); + return { ...state }; + } +} + +export default () => { + const components = React.useContext(MDXContext); + const [state, dispatch] = React.useReducer(reducer, initialState); + const onSubmit = React.useCallback( + (event: FormEvent) => { + event.preventDefault(); + const body = + new FormData(event.currentTarget as HTMLFormElement) + .get("body") + ?.toString() || ""; + if (body.length === 0) return; + dispatch({ + type: "add", + body + }); + }, + [dispatch] + ); + + const H1 = components.h1 || "h1"; + const Ul = components.ul || "ul"; + const Li = components.li || "li"; + + return ( + <> +

ToDo List

+
+ + +
+
    + {[...state.todo].map(([key, body]) => ( +
  • + dispatch({ type: "delete", key })} + /> + {body} +
  • + ))} +
+ + ); +}; diff --git a/tsconfig.json b/tsconfig.json index e0f0d35..ff58703 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -17,7 +17,8 @@ "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, - "jsx": "preserve" + "jsx": "preserve", + "downlevelIteration": true }, "exclude": ["node_modules"], "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"]