Skip to content

Instantly share code, notes, and snippets.

@djirdehh
Created May 2, 2024 17:03
Show Gist options
  • Save djirdehh/a1e03a717b5c4555a3c99a8e620eb77d to your computer and use it in GitHub Desktop.
Save djirdehh/a1e03a717b5c4555a3c99a8e620eb77d to your computer and use it in GitHub Desktop.
import { useActionState } from "react";
const addTodo = async (todoDetails) => {
const response = await fetch("https://dummyjson.com/todos/add", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(todoDetails),
});
return response.json();
};
const action = async (_, formData) => {
try {
const newlyAddedTodo = await addTodo({
todo: formData.get("todo"),
userId: 5,
completed: formData.get("completed") === "checked",
});
return {
message: "Todo has successfully been added!",
payload: newlyAddedTodo,
};
} catch {
return { message: "Uh oh, Todo could not be added :(", payload: null };
}
};
export function AddTodoComponent() {
const [actionState, formAction, isPending] = useActionState(action, null);
return (
<form action={formAction}>
<h2>Add Todo 📝</h2>
<div>
<label>Title</label>
<input type="text" name="todo" disabled={isPending} />
</div>
<div>
<label>Completed</label>
<input
type="checkbox"
name="completed"
value="checked"
disabled={isPending}
/>
</div>
<button type="submit" disabled={isPending}>
Add Todo
</button>
<div className="todo-details">
{isPending ? <h4>Pending...</h4> : null}
<h4>{actionState?.message}</h4>
{actionState?.payload ? (
<div>
<p>
<b>Title: </b>
{actionState?.payload.todo}
</p>
<p>
<b>Completed: </b>
{actionState?.payload.completed ? "Yes" : "No"}
</p>
</div>
) : null}
</div>
</form>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment