-
Notifications
You must be signed in to change notification settings - Fork 0
/
ReactQuery.txt
204 lines (128 loc) · 6.79 KB
/
ReactQuery.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
----------------------------------- REACT QUERY -----------------------------------
** Main points of react query
BASIC QUERY
POLL DATA
RQ DEV TOOL
CREATE REUSEABLE REACT TOOLS
QUERY BY ID
PARELLEL QUERY
DYNAMIC QUERIES
DEPENDANT QUERIES
INFINTE & PAGINATED QUERY
1 . install package react-query
2 . import {QueryClientProvider , QueryClient } from 'rect-query;
3 . Wrap the component on which you want impact of react -query with QueryClientProvider
4 . make a instance of QueryClient() usind new and pass it as a props in <QueryClientProvider></QueryClientProvider>
** useQuery hook
const {isLoading , data , error , isError} = useQuery('query-name-as-per-use , (()=>{
return axios.get('url')
}))
Beacuse of this default destructuring which resturn loading state and data , we do not need to use additional state for maintain mean time (loading time) , and also return error flags and isError flag to handle error , reduce lines for try catch block
*** Devtool
import {ReactQueryDevTools} from 'rect-query/devtool
and wrap all the component with <ReactQueryDevTools> , it is a kind of siblling of browser develper tool , learn more about it later in the session
*** Query Cache
react query comes up with another mindblowing thing called query cache , will store query requeest (fetchd api ) for 5 min (which can be change) in cache memory , so each time in between givin duartion if some one re-visit the page , react query can easily fetch it from cache , no need to go for server .
Not enough ohk !!! evnen after serve fetch data react query goes for server to fetch data if there might be any change in data in between mintime (5 mins)
Still not enough !! ohk , here is more for you , react-query provide a "staleTime" for you to set a time , when react-query should fire background request for fetch new data (if there is any chnage in your dtabase for user , so you can set time as per your requirment , so react-query throws request afetr specfic time , by default the time is 0 min )
How to know it ? Is react -query provide any flag for it ?
Yes !!!!
const {isLoading , data , error , isError , isFetching } = useQuery('query-name-as-per-use , (()=>{
return axios.get('url')
},
{
cacheTime : 5min (default 5 min),
staleTime : 1 min (default 0 min),
refetchOnMount : true/false/always (default true ---> fetch each time component re-renders)
refetchOnWindowFocus : true/false/always (default true ---> fetch each time when tab chamge or window lose and gain focus again re-renders)
}
))
** Polling
polloing is important when we need continue updation in data , whether user update component irrecpective of any user action which causes rerender, or window focus (like stock market app)
polling fetch data in each period of interval irrecpective of any other factor
const {isLoading , data , error , isError , isFetching } = useQuery('query-name-as-per-use , (()=>{
return axios.get('url')
},
{
refetcInterval : 2000, (refetch data in every 2 sec)
refetchIntervalInBackground : 2000 (refetch data in every 2 sec , event if window losses focus)
}
))
*** Success and error callbcak
const onError = ()=>{
// do some side effect when error occurs
}
const onSuccess = ()=>{
// do some side effect when error occurs
}
const {isLoading , data , error , isError , isFetching } = useQuery('query-name-as-per-use , (()=>{
return axios.get('url')
},
{
refetcInterval : 2000, //(refetch data in every 2 sec)
refetchIntervalInBackground : 2000 , //(refetch data in every 2 sec , event if window losses focus)
onSuccess : onSuccess,
onError : onError
}
))
** Data tarsformation
we can even manuplate data we recive from serve , beacuse at front end configartion required for dispaly data might be diffrent
const onError = (error)=>{
// magically comes with default paremeter called error ,which contains all about error
// do some side effect when error occurs
}
const onSuccess = (data)=>{
// magically comes with default paremeter called data ,which contains all about data
// do some side effect when error occurs
}
const {isLoading , data , error , isError , isFetching } = useQuery('query-name-as-per-use , (()=>{
return axios.get('url')
}),
{
onSuccess : onSuccess,
onError : onError ,
select : (data) => {
const newData = data.map/filter/resduce // do any necessary operation
return newData
}
}
)
because of this cofigartion now , wherever we get data (in onSuccess) is with change configartion as we set in select query
*** Custom hook
we can make a custom hook by wrapping up it by a one function which returns useQuery hook , pass all necessary configartion for query through object type argument , and get it those parameter as props in custom hooks
example :
const useCustomQueryHook = (props)=>{
return useQuery(['query-name' , dependencies] , (()=>{
return axios.get('url')
}) , props)
}
// in another file
import useCustomQueryHook from './path'
const {isLoading , data , error , isError , isFetching}
= useCustomQueryHook({neccessary cinfigartion for query})
*** refetch (onClick)
just make any button , onClick you want to trigger an api request . useQuey gives us one more functionality in callles refetch .
const {refetch , and other things} = useQuery()
use this refetch in any button onClick={refetch} anf it will trigger api request.
<button onClick={refetch}></button>
**parallel query
const {data : asYouwant} = useQuery();
const {data : asYouwant1} = useQuery();
** Dynamic Query
When you want to trigger same api request for moere the one time at a same time , react-query comes with "useQueries"
const dynamicQuery = ({arrayOfId}: props)=>{
const result = useQueris(
arrayOfId.map((id)=>{
return {
querykey : ['name-of-query' , id],
queryFn : () => await axios.get('find/${id}')
}
})
)
}
** pagination
depends more on backend , but we can maintain old data while requesting for anothe page , so we do not need to shoe loading satatus , instead until react-query fetching new data , it shows old data . Give good user experiance (personaly I do not recomend this in envey sitaation)
// just add this configration
{
keepPreviousData : true,
}