Skip to content

Instantly share code, notes, and snippets.

@Jossdz
Created May 23, 2022 22:54
Show Gist options
  • Save Jossdz/e717f706ec3a114763778e64c76d76ad to your computer and use it in GitHub Desktop.
Save Jossdz/e717f706ec3a114763778e64c76d76ad to your computer and use it in GitHub Desktop.
Here's my code:
```jsx
import { redirect } from "@remix-run/node";
import { Form, useLoaderData, useTransition } from "@remix-run/react";
import axios from "axios";
export const loader = async () => {
const { data: posts } = await axios.get("http://localhost:3001/posts");
return { posts };
};
export const action = async ({ request }) => {
const formData = await request.formData();
let { title, _action, id } = Object.fromEntries(formData);
if (_action === "create") {
await axios.post("http://localhost:3001/posts", {
title
});
}
if (_action === "delete") {
await axios.delete(`http://localhost:3001/posts/${id}`);
}
return redirect("/examples/five");
};
export default () => {
const { posts } = useLoaderData();
const transition = useTransition();
const isAdding =
transition.state === "submitting" &&
transition.submission.formData.get("_action") === "create";
return (
<main>
<h1>Todos</h1>
<small>Example 5</small>
<Form method="post">
<fieldset>
<textarea name="title" />
<button type="submit" name="_action" value="create">
{isAdding ? "Adding" : "Add"} post
</button>
</fieldset>
</Form>
{posts?.map((post) => (
<div key={post.id}>
<p
style={{
opacity:
transition.submission?.formData?.get("id") === post.id
? 0.25
: 1
}}
>
{post.title}
</p>
<Form replace method="post">
<input type="hidden" name="id" value={post.id} />
<button type="submit" name="_action" value="delete">
Delete
</button>
</Form>
</div>
))}
</main>
);
};
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment