|
| 1 | +import { bind, Subscribe } from "@react-rxjs/core" |
| 2 | +import { createSignal } from "@react-rxjs/utils" |
| 3 | +import React, { useRef } from "react" |
| 4 | +import { concat, defer } from "rxjs" |
| 5 | +import { concatMap, switchMap } from "rxjs/operators" |
| 6 | + |
| 7 | +const { getTodos, postTodo } = (() => { |
| 8 | + let todos = [ |
| 9 | + { |
| 10 | + id: 0, |
| 11 | + title: "Grocery shopping", |
| 12 | + }, |
| 13 | + ] |
| 14 | + |
| 15 | + return { |
| 16 | + getTodos: async () => todos, |
| 17 | + postTodo: async (todo) => { |
| 18 | + todos = [ |
| 19 | + ...todos, |
| 20 | + { |
| 21 | + id: todos[todos.length - 1].id + 1, |
| 22 | + title: todo, |
| 23 | + }, |
| 24 | + ] |
| 25 | + }, |
| 26 | + } |
| 27 | +})() |
| 28 | + |
| 29 | +const [todoPost$, addTodo] = createSignal<string>() |
| 30 | + |
| 31 | +const todoResult$ = todoPost$.pipe(concatMap(postTodo)) |
| 32 | + |
| 33 | +const [useTodos] = bind( |
| 34 | + // When do we need to request todos? |
| 35 | + concat( |
| 36 | + // 1. One single time when starting |
| 37 | + defer(getTodos), |
| 38 | + // 2. Every time we have created a new todo |
| 39 | + todoResult$.pipe(switchMap(getTodos)), |
| 40 | + ), |
| 41 | + [], |
| 42 | +) |
| 43 | + |
| 44 | +function Todos() { |
| 45 | + const todos = useTodos() |
| 46 | + |
| 47 | + const ref = useRef<HTMLInputElement>() |
| 48 | + const handleAddClick = () => { |
| 49 | + addTodo(ref.current!.value) |
| 50 | + ref.current!.value = "" |
| 51 | + ref.current!.focus() |
| 52 | + } |
| 53 | + |
| 54 | + return ( |
| 55 | + <div> |
| 56 | + <input type="text" defaultValue="Do Laundry" ref={ref} /> |
| 57 | + <button onClick={handleAddClick}>Add Todo</button> |
| 58 | + |
| 59 | + <ul> |
| 60 | + {todos.map((todo) => ( |
| 61 | + <li key={todo.id}>{todo.title}</li> |
| 62 | + ))} |
| 63 | + </ul> |
| 64 | + </div> |
| 65 | + ) |
| 66 | +} |
| 67 | + |
| 68 | +export default function InvalidateQuery() { |
| 69 | + return ( |
| 70 | + <Subscribe fallback={<div>Loading...</div>}> |
| 71 | + <Todos /> |
| 72 | + </Subscribe> |
| 73 | + ) |
| 74 | +} |
0 commit comments