Since I'm new to React Query. One thing that got stuck with me is the select option in useQuery(). I'm unable to understand, how to use it properly.
If you can explain it, then it would be very helpful to me.
Also, I have other doubts in useQuery(), I can understand it, but don't know how to use it:
As per the react-query doc select option to select or transform parts of the query result.
Let's assume you have a list of fruits and vegetables in your database
[banana ,grapes ,coconut ,cabbage ,apple ,celery]
And you have a checkbox with the label Show items with letter 'C'.
There are two functions defined:
getList() ==> returns the whole list
getFilteredList(list) ==> takes the whole list as an argument and returns the list of items starting with the letter 'C'
Here is the code:
const [isChecked, setIsChecked]= useState(false); //to manage the status of the checkbox
const fallback=[];
const {data:list=fallback}= useQuery("list", getList,{
select: isChecked? (list)=>getFilteredList(list) : undefined
})
useQuery runs getList function and receives the full list from the server. Now if the checkbox is enabled i.e isChecked is true then the list will be passed to getFilteredList. Now the given list will be filtered and contain items starting with letter'C'. This new filtered list will replace the old whole list in the {data:list} of useQuery.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With