()
| 20 | } |
| 21 | |
| 22 | function Example() { |
| 23 | const queryClient = useQueryClient() |
| 24 | const [intervalMs, setIntervalMs] = React.useState(1000) |
| 25 | const [value, setValue] = React.useState('') |
| 26 | |
| 27 | const { status, data, error, isFetching } = useQuery({ |
| 28 | queryKey: ['todos'], |
| 29 | queryFn: async (): Promise<Array<string>> => { |
| 30 | const response = await fetch('/api/data') |
| 31 | return await response.json() |
| 32 | }, |
| 33 | // Refetch the data every second |
| 34 | refetchInterval: intervalMs, |
| 35 | }) |
| 36 | |
| 37 | const addMutation = useMutation({ |
| 38 | mutationFn: (add: string) => fetch(`/api/data?add=${add}`), |
| 39 | onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }), |
| 40 | }) |
| 41 | |
| 42 | const clearMutation = useMutation({ |
| 43 | mutationFn: () => fetch(`/api/data?clear=1`), |
| 44 | onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }), |
| 45 | }) |
| 46 | |
| 47 | if (status === 'pending') return <h1>Loading...</h1> |
| 48 | if (status === 'error') return <span>Error: {error.message}</span> |
| 49 | |
| 50 | return ( |
| 51 | <div> |
| 52 | <h1>Auto Refetch with stale-time set to {intervalMs}ms</h1> |
| 53 | <p> |
| 54 | This example is best experienced on your own machine, where you can open |
| 55 | multiple tabs to the same localhost server and see your changes |
| 56 | propagate between the two. |
| 57 | </p> |
| 58 | <label> |
| 59 | Query Interval speed (ms):{' '} |
| 60 | <input |
| 61 | value={intervalMs} |
| 62 | onChange={(ev) => setIntervalMs(Number(ev.target.value))} |
| 63 | type="number" |
| 64 | step="100" |
| 65 | />{' '} |
| 66 | <span |
| 67 | style={{ |
| 68 | display: 'inline-block', |
| 69 | marginLeft: '.5rem', |
| 70 | width: 10, |
| 71 | height: 10, |
| 72 | background: isFetching ? 'green' : 'transparent', |
| 73 | transition: !isFetching ? 'all .3s ease' : 'none', |
| 74 | borderRadius: '100%', |
| 75 | transform: 'scale(2)', |
| 76 | }} |
| 77 | /> |
| 78 | </label> |
| 79 | <h2>Todo List</h2> |
nothing calls this directly
no test coverage detected
searching dependent graphs…