Created
August 19, 2023 14:49
-
-
Save pkellner/03cd623f4274d3f2ef087fd21e8dccb8 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 "server-only"; | |
import ToDoItem from "../../components/todo/ToDoItem"; | |
import ToDoItemClient from "../../components/todo/ToDoItemClient"; | |
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); | |
export default async function ToDoList() { | |
const url = "http://localhost:4000/todos"; | |
const res = await fetch(url,{ | |
next: { | |
revalidate: 0, | |
} | |
}); | |
const results = await res.json(); | |
const todoList = results; | |
await sleep(1000); | |
return ( | |
<div className="tasks"> | |
{todoList.map((toDo) => { | |
return ( | |
<ToDoItemClient toDo={toDo} key={toDo.id}> | |
<ToDoItem toDo={toDo} /> | |
</ToDoItemClient> | |
); | |
})} | |
</div> | |
); | |
} | |
"use client"; | |
import { useRouter } from "next/navigation"; | |
import { useTransition } from "react"; | |
export default function ToggleImportantButton({ toDo }) { | |
async function toggleIt() { | |
try { | |
const updatedImportant = !toDo.important; | |
const updatedTodo = { ...toDo, important: updatedImportant }; | |
// Send the updated todo to the server | |
const url = `http://localhost:4000/todos/${toDo.id}` | |
const response = await fetch(url, { | |
method: "PUT", | |
headers: { | |
"Content-Type": "application/json", | |
}, | |
body: JSON.stringify(updatedTodo), | |
}); | |
if (!response.ok) { | |
throw new Error("Something went haywire with the network response!"); | |
} | |
router.refresh(); | |
} catch (error) { | |
console.error("uh oh! A glitch in the matrix:", error); | |
} | |
} | |
const router = useRouter(); | |
const [isPending, startTransition] = useTransition(); | |
return ( | |
<button | |
className="btn btn-info btn-sm" | |
onClick={() => startTransition(toggleIt)} | |
> | |
Toggle Important | |
</button> | |
); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment