|
| 1 | +/** @jsxImportSource solid-js */ |
| 2 | + |
| 3 | +import { render } from "@solidjs/web"; |
| 4 | +import type { Post } from "jsonplaceholder-types/types/post"; |
| 5 | +import type { User } from "jsonplaceholder-types/types/user"; |
| 6 | +import { |
| 7 | + createMemo, |
| 8 | + createSignal, |
| 9 | + For, |
| 10 | + isPending, |
| 11 | + Loading, |
| 12 | + Match, |
| 13 | + onCleanup, |
| 14 | + Switch, |
| 15 | +} from "solid-js"; |
| 16 | + |
| 17 | +const urlBase = "https://jsonplaceholder.typicode.com"; |
| 18 | + |
| 19 | +async function fetchUsers() { |
| 20 | + const ctrl = new AbortController(); |
| 21 | + onCleanup(() => ctrl.abort()); |
| 22 | + const response = await fetch(`${urlBase}/users`, { signal: ctrl.signal }); |
| 23 | + return await response.json() as User[]; |
| 24 | +} |
| 25 | + |
| 26 | +async function fetchPosts(userId: number) { |
| 27 | + const ctrl = new AbortController(); |
| 28 | + onCleanup(() => ctrl.abort()); |
| 29 | + const response = await fetch( |
| 30 | + `${urlBase}/posts?userId=${userId}`, |
| 31 | + { signal: ctrl.signal }, |
| 32 | + ); |
| 33 | + return await response.json() as Post[]; |
| 34 | +} |
| 35 | + |
| 36 | +function App() { |
| 37 | + const [selectedUserId, setSelectedUserId] = createSignal<number>(); |
| 38 | + const users = createMemo(() => fetchUsers()); |
| 39 | + const posts = createMemo(() => { |
| 40 | + const userId = selectedUserId(); |
| 41 | + return userId !== undefined ? fetchPosts(userId) : []; |
| 42 | + }); |
| 43 | + |
| 44 | + return ( |
| 45 | + <> |
| 46 | + <h1>Buildless SolidJS 2 app</h1> |
| 47 | + <Loading fallback={<p>Loading Users...</p>}> |
| 48 | + <label> |
| 49 | + Select User: |
| 50 | + <select |
| 51 | + onChange={function handleChange(event) { |
| 52 | + setSelectedUserId(+event.currentTarget.value); |
| 53 | + }} |
| 54 | + > |
| 55 | + <option hidden selected></option> |
| 56 | + <For each={users()}> |
| 57 | + {(user) => ( |
| 58 | + <option value={user().id}> |
| 59 | + @{user().username}: {user().name} |
| 60 | + </option> |
| 61 | + )} |
| 62 | + </For> |
| 63 | + </select> |
| 64 | + </label> |
| 65 | + </Loading> |
| 66 | + <Switch> |
| 67 | + <Match when={selectedUserId() !== undefined}> |
| 68 | + <Loading fallback={<p>Loading Posts...</p>}> |
| 69 | + <ul> |
| 70 | + <For each={posts()}> |
| 71 | + {(post) => <li>{post().title}</li>} |
| 72 | + </For> |
| 73 | + </ul> |
| 74 | + </Loading> |
| 75 | + </Match> |
| 76 | + <Match when={!isPending(users)}> |
| 77 | + <p>Select User to view posts</p> |
| 78 | + </Match> |
| 79 | + </Switch> |
| 80 | + <p> |
| 81 | + Data Source: |
| 82 | + <a href="https://jsonplaceholder.typicode.com/" target="_blank"> |
| 83 | + JSONPlaceholder |
| 84 | + </a> |
| 85 | + </p> |
| 86 | + </> |
| 87 | + ); |
| 88 | +} |
| 89 | + |
| 90 | +render(() => <App />, document.body); |
0 commit comments