Created
August 14, 2022 03:31
-
-
Save joeelmahallawy/4c02cc8816bb24bc95ae8664e6a9f676 to your computer and use it in GitHub Desktop.
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
import { Box, Button, Center, Input, Title } from "@mantine/core"; | |
import React, { useEffect, useState } from "react"; | |
const IndexPage = () => { | |
const [newTodo, setNewTodo] = useState(""); | |
const [todos, setTodos] = useState<{ id: string; task: string }[]>([]); | |
useEffect(() => { | |
(async () => { | |
const getTodos = await fetch(`/api/todos`, { method: "GET" }); | |
const data = await getTodos.json(); | |
setTodos([...data.results]); | |
})(); | |
}, []); | |
console.log(todos); | |
return ( | |
<Center style={{ flexDirection: "column", padding: 10 }}> | |
<Title>Next.js + Serve todo app</Title> | |
<Center style={{ gap: 5, marginTop: 10 }}> | |
<Input.Wrapper label="New task"> | |
<Input | |
onChange={(e) => setNewTodo(e.currentTarget.value)} | |
style={{ width: "300px" }} | |
placeholder="e.g. Send email to my boss" | |
/> | |
</Input.Wrapper> | |
<Button | |
onClick={async () => { | |
const randomID = Math.random().toString(36); | |
const upload = await fetch(`/api/todos`, { | |
method: "POST", | |
body: JSON.stringify({ | |
todo: newTodo, | |
randomID, | |
}), | |
}); | |
if (!upload.ok) alert("Error adding todo"); | |
// @ts-ignore | |
else setTodos([...todos, { id: randomID, task: newTodo }]); | |
}} | |
mt="auto" | |
> | |
Create new todo | |
</Button> | |
</Center> | |
<Box> | |
<Title>Todo</Title> | |
{todos.map((todo, i) => ( | |
<Center | |
sx={(theme) => ({ | |
padding: 10, | |
marginTop: 10, | |
background: theme.colors.gray[2], | |
justifyContent: "space-between", | |
gap: 10, | |
minWidth: "300px", | |
})} | |
key={i} | |
> | |
{todo.task} | |
<Center | |
sx={{ | |
width: "25px", | |
height: "25px", | |
borderRadius: "100%", | |
background: "gray", | |
color: "white", | |
"&:hover": { cursor: "pointer" }, | |
}} | |
onClick={async () => { | |
const deleteTodo = await fetch(`/api/todos`, { | |
method: "DELETE", | |
body: JSON.stringify({ id: todo.id }), | |
}); | |
const data = await deleteTodo.json(); | |
setTodos(todos.filter((val) => val.id !== todo.id)); | |
console.log(data); | |
}} | |
> | |
– | |
</Center> | |
</Center> | |
))} | |
</Box> | |
</Center> | |
); | |
}; | |
export default IndexPage; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment