Skip to content

Instantly share code, notes, and snippets.

@ryanflorence
Created April 12, 2022 19:52
Show Gist options
  • Save ryanflorence/16fc476c30d373b859d8e00b8a0c68e8 to your computer and use it in GitHub Desktop.
Save ryanflorence/16fc476c30d373b859d8e00b8a0c68e8 to your computer and use it in GitHub Desktop.
import "./index.css";
import React from "react";
import ReactDOM from "react-dom";
import {
DataBrowserRouter,
Route,
useLoaderData,
Form,
useNavigation,
} from "react-router-dom";
function sleep(ms: number) {
return new Promise((res) => setTimeout(res, ms));
}
async function getTasks() {
await sleep(Math.random() * 1000);
let json = localStorage.getItem("tasks");
return json ? JSON.parse(json) : [];
}
async function setTasks(tasks: string[]) {
await sleep(Math.random() * 1000);
localStorage.setItem("tasks", JSON.stringify(tasks));
}
async function addTask(task: string) {
await sleep(Math.random() * 1000);
let tasks = (await getTasks()) as unknown as string[];
tasks.push(task);
await setTasks(tasks);
return task;
}
ReactDOM.render(
<React.StrictMode>
<DataBrowserRouter fallbackElement={<div>Loading...</div>}>
<Route
path="/"
loader={async () => getTasks()}
action={async ({ formData }) => {
let text = formData.get("text") as string;
return addTask(text);
}}
element={<Tasks />}
/>
</DataBrowserRouter>
</React.StrictMode>,
document.getElementById("root")
);
function Tasks() {
let data = useLoaderData();
let ref = React.useRef<HTMLInputElement>(null);
let navigation = useNavigation();
let busy =
navigation.state === "submitting" || navigation.state === "loading";
React.useEffect(() => {
if (!busy) {
ref.current?.select();
}
}, [busy]);
return (
<div>
{data.map((task: string, i: number) => (
<div key={i}>{task}</div>
))}
<Form method="post">
<fieldset disabled={busy}>
<input ref={ref} name="text" placeholder="New Task" />{" "}
<button type="submit">{busy ? "Adding..." : "Add"}</button>
</fieldset>
</Form>
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment