Open History to see the last commit
1import React from 'react'
2import axios from 'axios'
3β
4import {
5 useQuery,
6 useQueryClient,
7 useMutation,
8 QueryClient,
9 QueryClientProvider,
10} from 'react-query'
11import { ReactQueryDevtools } from 'react-query/devtools'
12β
13const queryClient = new QueryClient()
14β
15export default function App() {
16 return (
17 <QueryClientProvider client={queryClient}>
18 <Example />
19 </QueryClientProvider>
20 )
21}
22β
23function Example() {
24 const queryClient = useQueryClient()
25β
26 const { status, data, error } = useQuery('user', async () => {
27 const res = await axios.get('/api/user')
28 return res.data
29 })
30β
31 const logoutMutation = useMutation(logout, {
32 onSuccess: () => queryClient.invalidateQueries('user'),
33 })
34β
35 const loginMutation = useMutation(login, {
36 onSuccess: () => queryClient.invalidateQueries('user'),
37 })
38β
39 return (
40 <div>
41 <p>
42 In this example, you should open two tabs, log in or out on one tab,
43 then focus the other to see it sync up! (Pro Tip: Do NOT use incognito
44 tabs)
45 </p>
46 {status === 'loading' ? (
47 <h1>Loading...</h1>
48 ) : status === 'error' ? (
49 <span>Error: {error.message}</span>
50 ) : data.loggedIn ? (
51 <div>
52 <h1>Welcome, {data.name}</h1>
53 {/* eslint-disable-next-line jsx-a11y/alt-text */}
54 <img src={data.avatar} width={80} />
55 <div>
56 <button
57 onClick={() => {
58 logoutMutation.mutate()
59 }}
60 >
61 Logout
62 </button>
63 </div>
64 </div>
65 ) : (
66 <div>
67 <h1>Please login</h1>
68 <div>
69 <button
70 onClick={() => {
71 loginMutation.mutate()
72 }}
73 >
74 Login
75 </button>
76 </div>
77 </div>
78 )}
79 <ReactQueryDevtools initialIsOpen />
80 </div>
81 )
82}
83β
84function login() {
85 document.cookie = 'swr-test-token=swr;'
86}
87β
88function logout() {
89 document.cookie = 'swr-test-token=; expires=Thu, 01 Jan 1970 00:00:01 GMT;'
90}