Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

index.js

68 lines1.6 KB

1import React from 'react'
2import fetch from '../libs/fetch'
3​
4import { useQuery, useMutation, setQueryData } from 'react-query'
5​
6export default () => {
7 const [text, setText] = React.useState('')
8 const { data, isLoading, isFetching } = useQuery('todos', () =>
9 fetch('/api/data')
10 )
11​
12 const [mutatePostTodo] = useMutation(
13 text =>
14 fetch('/api/data', {
15 method: 'POST',
16 body: JSON.stringify({ text }),
17 }),
18 {
19 refetchQueries: ['todos'],
20 // to revalidate the data and ensure the UI doesn't
21 // remain in an incorrect state, ALWAYS trigger a
22 // a refetch of the data, even on failure
23 refetchQueriesOnFailure: true,
24 }
25 )
26​
27 async function handleSubmit(event) {
28 event.preventDefault()
29 // mutate current data to optimistically update the UI
30 // the fetch below could fail, so we need to revalidate
31 // regardless
32​
33 setQueryData('todos', [...data, text], {
34 shouldRefetch: false,
35 })
36​
37 try {
38 // send text to the API
39 await mutatePostTodo(text)
40 setText('')
41 } catch (err) {
42 console.error(err)
43 }
44 }
45​
46 return (
47 <div>
48 <form onSubmit={handleSubmit}>
49 <input
50 type="text"
51 onChange={event => setText(event.target.value)}
52 value={text}
53 />
54 <button>Create</button>
55 </form>
56 <ul>
57 {isLoading ? (
58 'Loading...'
59 ) : (
60 <>
61 {data ? data.map(datum => <li key={datum}>{datum}</li>) : null}
62 <div>{isFetching ? 'Updating in background...' : ' '}</div>
63 </>
64 )}
65 </ul>
66 </div>
67 )