@evobug_com/safe-ts-skill 0.0.0-stage → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,230 @@
1
+ # Pattern catalogue: React
2
+
3
+ React components and hooks, before and after, in the convention of
4
+ [patterns-core.md](patterns-core.md): ` ```tsx bad <rules> ` is the code before with the rules
5
+ `safe-ts check` reports (none listed: the checker is silent), ` ```tsx good ` the target.
6
+ Examples import `fetchUser(id, signal)` from `./api`: a request function that returns
7
+ `Promise<Result<User, ApiError>>`, as in [patterns-core.md](patterns-core.md#requests-return-a-result).
8
+
9
+ SAFE-TS leaves the rules of hooks, effect dependencies and in-place state changes to
10
+ eslint-plugin-react-hooks, and JSX keys to your linter. React guide pages: Async state, State
11
+ and props, Errors in handlers, Cleanup, Security, Setup.
12
+
13
+ ## Contents
14
+
15
+ - [A loading, error, data trio](#a-loading-error-data-trio)
16
+ - [An effect that loads without cleanup](#an-effect-that-loads-without-cleanup)
17
+ - [Module state](#module-state)
18
+ - [A prop changed by the child](#a-prop-changed-by-the-child)
19
+ - [A Result returned to React](#a-result-returned-to-react)
20
+ - [HTML from outside](#html-from-outside)
21
+
22
+ ## A loading, error, data trio
23
+
24
+ `loading`, `error` and `data` states set from an effect can disagree, and an older response can
25
+ overwrite a newer one. `useTask` from `@evobug_com/safe-ts-react/task` keeps one `AsyncState`,
26
+ aborts the previous run (its `signal` fires) when a new one starts, and aborts the run in
27
+ progress on unmount. `run` is the same function on every render, so it goes in the effect's
28
+ dependencies.
29
+
30
+ ```tsx bad react-async-race react-split-state
31
+ import { useEffect, useState } from "react";
32
+ import { isErr } from "@evobug_com/safe-ts-std/result";
33
+ import { fetchUser, type User } from "./api";
34
+
35
+ export function Profile({ id }: { id: string }) {
36
+ const [loading, setLoading] = useState(false);
37
+ const [failed, setFailed] = useState("");
38
+ const [user, setUser] = useState<User>();
39
+
40
+ useEffect(() => {
41
+ const load = async (): Promise<void> => {
42
+ setLoading(true);
43
+ const result = await fetchUser(id);
44
+ setLoading(false);
45
+ if (isErr(result)) setFailed(result.error.message);
46
+ else setUser(result);
47
+ };
48
+ void load();
49
+ }, [id]);
50
+
51
+ if (loading) return <p>Loading…</p>;
52
+ if (failed !== "") return <p>{failed}</p>;
53
+ return <p>{user?.name}</p>;
54
+ }
55
+ ```
56
+
57
+ ```tsx good
58
+ import { useEffect } from "react";
59
+ import { Match } from "@evobug_com/safe-ts-react/match";
60
+ import { useTask } from "@evobug_com/safe-ts-react/task";
61
+ import { fetchUser } from "./api";
62
+
63
+ export function Profile({ id }: { id: string }) {
64
+ const { state, run } = useTask((signal, id: string) => fetchUser(id, signal));
65
+
66
+ useEffect(() => {
67
+ run(id).catch((reason: unknown) => console.error(reason));
68
+ }, [id, run]);
69
+
70
+ return (
71
+ <Match
72
+ on={state}
73
+ Loading={() => <p>Loading…</p>}
74
+ Ready={({ value }) => <p>{value.name}</p>}
75
+ Failed={({ error }) => <p>Couldn't load the user: {error.message}</p>}
76
+ _={() => undefined}
77
+ />
78
+ );
79
+ }
80
+ ```
81
+
82
+ - `run(id)` rejects only when the work threw instead of returning an `Err`: a bug, which
83
+ `useTask` doesn't turn into `Failed`. Log it, as above.
84
+ - `<Match>` takes a function per variant; without `_`, a missing variant is a type error. When
85
+ every variant renders the same element, compute it with `match` from
86
+ `@evobug_com/safe-ts-std/enum` instead.
87
+
88
+ ## An effect that loads without cleanup
89
+
90
+ Where `useTask` doesn't fit, an effect that loads must stop the run it no longer needs: return a
91
+ cleanup that aborts the request.
92
+
93
+ ```tsx good
94
+ import { useEffect, useState } from "react";
95
+ import { isErr } from "@evobug_com/safe-ts-std/result";
96
+ import { fetchUser, type User } from "./api";
97
+
98
+ export function Name({ id }: { id: string }) {
99
+ const [user, setUser] = useState<User>();
100
+
101
+ useEffect(() => {
102
+ const controller = new AbortController();
103
+ const load = async (): Promise<void> => {
104
+ const result = await fetchUser(id, controller.signal);
105
+ if (!controller.signal.aborted && !isErr(result)) setUser(result);
106
+ };
107
+ void load();
108
+ return () => controller.abort();
109
+ }, [id]);
110
+
111
+ return <p>{user?.name ?? "…"}</p>;
112
+ }
113
+ ```
114
+
115
+ ## Module state
116
+
117
+ A `let` at the top of a file is one value for every instance, every test and (with server
118
+ rendering) every request (`no-mutable-global`). Keep it in the component, in a common parent, or
119
+ in a context whose provider creates it.
120
+
121
+ ```tsx bad no-mutable-global
122
+ let clicks = 0;
123
+
124
+ export function Counter() {
125
+ return <button onClick={() => { clicks += 1; }}>Clicked</button>;
126
+ }
127
+ ```
128
+
129
+ ```tsx good
130
+ import { useState } from "react";
131
+
132
+ export function Counter() {
133
+ const [clicks, setClicks] = useState(0);
134
+ return <button onClick={() => setClicks((n) => n + 1)}>Clicked {clicks} times</button>;
135
+ }
136
+ ```
137
+
138
+ ## A prop changed by the child
139
+
140
+ Props are the parent's data; changing an object reached through them changes it without telling
141
+ React (`no-param-mutation`). Ask the parent with a callback.
142
+
143
+ ```tsx bad no-param-mutation
144
+ type Todo = { title: string; done: boolean };
145
+
146
+ export function TodoItem({ todo }: { todo: Todo }) {
147
+ return (
148
+ <label>
149
+ <input type="checkbox" checked={todo.done} onChange={() => { todo.done = !todo.done; }} />
150
+ {todo.title}
151
+ </label>
152
+ );
153
+ }
154
+ ```
155
+
156
+ ```tsx good
157
+ type Todo = { readonly title: string; readonly done: boolean };
158
+
159
+ export function TodoItem({ todo, onToggle }: { todo: Todo; onToggle: () => void }) {
160
+ return (
161
+ <label>
162
+ <input type="checkbox" checked={todo.done} onChange={onToggle} />
163
+ {todo.title}
164
+ </label>
165
+ );
166
+ }
167
+ ```
168
+
169
+ ## A Result returned to React
170
+
171
+ React drops what a handler returns, so `onClick={archive}` with a `Result` loses the error
172
+ (`must-use-result`). The handler decides what the user sees.
173
+
174
+ ```tsx bad must-use-result
175
+ import { err, type Result } from "@evobug_com/safe-ts-std/result";
176
+
177
+ function archive(): Result<void, string> {
178
+ return err("Only drafts can be archived");
179
+ }
180
+
181
+ export function Toolbar() {
182
+ return <button onClick={archive}>Archive</button>;
183
+ }
184
+ ```
185
+
186
+ ```tsx good
187
+ import { useState } from "react";
188
+ import { err, isErr, type Option, type Result } from "@evobug_com/safe-ts-std/result";
189
+
190
+ function archive(): Result<void, string> {
191
+ return err("Only drafts can be archived");
192
+ }
193
+
194
+ export function Toolbar() {
195
+ const [problem, setProblem] = useState<Option<string>>();
196
+ const onArchive = (): void => {
197
+ const archived = archive();
198
+ setProblem(isErr(archived) ? archived.error : undefined);
199
+ };
200
+ return (
201
+ <>
202
+ <button onClick={onArchive}>Archive</button>
203
+ {problem !== undefined && <p>{problem}</p>}
204
+ </>
205
+ );
206
+ }
207
+ ```
208
+
209
+ ## HTML from outside
210
+
211
+ `dangerouslySetInnerHTML` with text from a user or the network can run script
212
+ (`react-dangerous-html`). Render text; when it must be HTML, call the sanitizer in the prop.
213
+ React 19 neutralises `javascript:` URLs in `href`; on React 18, bind URLs from users through
214
+ `safeHref` from `@evobug_com/safe-ts-std/url`.
215
+
216
+ ```tsx bad react-dangerous-html
217
+ type Comment = { readonly author: string; readonly body: string };
218
+
219
+ export function CommentView({ comment }: { comment: Comment }) {
220
+ return <div dangerouslySetInnerHTML={{ __html: comment.body }} />;
221
+ }
222
+ ```
223
+
224
+ ```tsx good
225
+ declare function sanitizeHtml(html: string): string;
226
+
227
+ export function Article({ html }: { html: string }) {
228
+ return <div dangerouslySetInnerHTML={{ __html: sanitizeHtml(html) }} />;
229
+ }
230
+ ```