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