React Query

 Fetching data with react Query

n

 

 How to fetch it 

 Common pattern notice whuile using react query is that query fn is defined elsewhere

 Handling error with react query

React Query is awesome as it reduces 15 lines of data fetching using useeffect to just 3 lines

 React Query Dev Tools

1)Import in app.js

2) before closing provider tag add this line

 

 lowecase t

 Query cache

Query Cache is extremely important. When react query fetches the data for the first time. It caches the data. So,when we wil next go to the page again it will not show loading,,, again and instead it will show cached data. However, react query knows that the data mighnt be fresh so it will do a background ccheck and if new data has come than it will reload else it will keep the data as it is,,..

so no flikceringor loading everytime data has been fetched

 Iniitally isLoading and isFetching both are true

but at secodn time isLoading will be false

Default caching time == 5 mins

 Stale Time

If you know our data is not changing too often than we can reduce multiple network req

 

 Our query will have fresh for next 30 sec and no additonal data fetching will occur for that period.

default stale time is 0 sec

Refetch Defaults

Refetchonmount -> fetch data everytime on mount /goes to that page

if false, only fetch for the first time

 or true/false

true is the best option

Refetchonwindows focus

data will refetch when we go to that window and not other time

or always

data will refetch wheter stale or not

Polling with react query

Not imp for me currrently

fetching data with regular intervals

 by default false

Sutomatic refetch lose focus on bg


 useQuery on click

1) disabed fetch on mount


enabled = false => not mount data on fetching

2) fetch on click

 Add refetch to manually trigger 

However, stale time,cache is still true..

Sucess and error callback


 Retry 3 times before error callback fired

also,we can get the error data by passing a parenthesis in the callback

 

Data Transformation 


We do this by select method

select automatically gets the data from the api

Custom Query Hook


 

 Query by Id

 

 Add Link to Navigaate tospecific page

Add anothetr hook for the specific page


 Now modifty the page

 

 To shor the code

 Now need to pass parameter to fetchSuper hero ..

instead just destructure in the function and get queryKey which is the array defined below..and get the index 1 element which is actually the id

Parallel Queries

Data are fetched in parrell 

 Alias the data to get it


Dynamic Parrell Queries

1) use usequeries instead of usequery

2) functions key are changing as diff method

3) retruns an array of data

we are using like this so as to not violate law of hooks

we can use console.log({}) to fetch the data in object


Dependednt queries

It is json server so users and channels are diff api routes

 

 enabled fetches data only when channelId exists

Disabled-status idle network req doesnt trigger when channelid doestnt exist

Double exclamation converts an object to truthy/falsy


 

Initial Query Data

Using initail query we can show the same data so as to avoid loading and fetch rest data after fetching

S1 :import queryClient to get hold of cache data of the website


s2 ->


 a) get initial data using initailData fn

b) find that element

c) if element exists than return that else return undefined

d) point to not that there shoudl return undefined ..than what will react query will do is do an hard reload where it will again fetch the data if data is not available.

Paginated Queries

Setup:

 8 object to display ,list of colors

To Note

 

React query limit gives 2 per page and page shows the next page


 Add state variable

pass page number to fetch colors

3) add next prev button to change page

 disabled at page4 and 1 resptciverly

 Now if I add keepreviousdata than the prev data will still show till new data is fetched ..so as to not show any loading..

However, we can turn on the isFetching flag to show a spinner

After fetching data is done new data is swapped out from old data seamlessly

Helps in prveenting layout shift

 Infinite queries

Show two additonal colors on every click... we can also do infiinte scroll as well

S1  use useinfinitequery and use pageParams

 

S2 Change pageparam

use getNextPageParam toincrease page number

hasNextPage helps to enable disable load more btn

 fetchnextpage helps to get the nextpage

 isFetching and isFetchingNextPage

 Wrong as infiinte query fetches data in diff way

 data gets two value group and index 


Mutations

1)import useMutation

 

 Query Invalidation

By invalidation a query react-query will refetch that quewry

 Handling Mutation Response

Instead if wasting another netwrok call if we want to directly get the date than we can use the response data instaed(if data is returned ofcourse)

 Optismitic Updates

It is done by updating data first before network request so as to give assurance that your app is blazing fast.Assumption that no error can occured

 


First get a id as well as we are missing the id in fetching

 

 We need to also return a data just incase mutation errors out

 Axios Interceptor

 

nnn

Comments

Popular posts from this blog

Form Part 2

Event mini project by Thapa#33

De-mystifying 'this' keyword of Javascript