Created
July 8, 2024 17:29
-
-
Save ArturBaybulatov/3143f912676ae0140a1473938c6a79b2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import ky from 'ky' | |
| import { makeAutoObservable } from 'mobx' | |
| import { observer } from 'mobx-react-lite' | |
| import { useState } from 'react' | |
| import { queryClient } from 'src/singletons/query-client/queryClient' | |
| import { fromQuery } from './_utils/fromQuery' | |
| type User = { | |
| email: string | |
| id: number | |
| } | |
| class Store { | |
| selectedUserId?: User['id'] | |
| usersQuery = fromQuery(queryClient, { | |
| queryFn: () => ky.get('https://jsonplaceholder.org/users').json<User[]>(), | |
| queryKey: ['users'] as const, | |
| }) | |
| constructor() { | |
| makeAutoObservable(this, undefined, { autoBind: true }) | |
| } | |
| get selectedUser() { | |
| const resource = fromQuery(queryClient, { | |
| queryFn: async ({ queryKey: [, userId] }) => { | |
| if (!userId) return null | |
| return await ky.get(`https://jsonplaceholder.org/users/${userId}`).json<User>() | |
| }, | |
| queryKey: ['user', this.selectedUserId] as const, | |
| }) | |
| return resource.current().data | |
| } | |
| get users() { | |
| return this.usersQuery.current().data ?? [] | |
| } | |
| } | |
| export const ExampleView = observer(() => { | |
| const [store] = useState(() => new Store()) | |
| return ( | |
| <div> | |
| <div> | |
| <div>Select a user:</div> | |
| <select | |
| onChange={({ target: { value } }) => { | |
| store.selectedUserId = +value | |
| }} | |
| > | |
| {store.users.map(user => ( | |
| <option key={user.id} value={user.id}> | |
| {user.email} | |
| </option> | |
| ))} | |
| </select> | |
| </div> | |
| <div> | |
| <div>Selected user ID:</div> | |
| <div>{store.selectedUserId}</div> | |
| </div> | |
| <div> | |
| <div>Selected user:</div> | |
| <div>{store.selectedUser?.email}</div> | |
| </div> | |
| </div> | |
| ) | |
| }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment