useQuery to populate dropdown
Hello everyone, what I'm trying to do is using the result of useQuery to populate a dropdown.
I discovered useQuery has a
select parameter that I can use to perform actions when I fetch the data (but using that I cannot return data anymore, or at least I can, but if I use the select parameter to modify a global status, then I return the data from the select function, it will cause an infinite loop, as the same as modifying a global state using the returned {data} value).
My problem is: from what I understood the best-practice is to use the {data} returned from useQuery to populate my dropdown, but this dropdown is associated with a Zustand global state that keeps track of the currently-selected element. If I initialize my global state with undefined everything goes well, but I want to initialize my global state with one selected item right after fetching the items.
My solution would be to use the select parameter to set 2 global states: one for saving the list of elements fetched and one for saving the selected item, but this could create problems when the query is re-fetched.
I hope my problem is clear, how do you handle situations like this?4 Replies
like-goldOP•3y ago
Update:
I managed to solve it, but it still hase some errors on "uncontrolled" values. Keeping the list of items as the result of useQuery, using only one global state to save the selected item and using an useEffect for setting the first default element after the query.
Bus as I said before, if you know the best-practice on how to do this I would be glad to hear you!
Any helpful suggestion about it? The problem is basically select one default value from the list I fetch from the backend. Is there any smart way to do it?
I feel this library is so powerful, but I need to grasp every bit of it to use it.
metropolitan-bronze•3y ago
Using the query data to populate the dropdown and then a useeffect to select the default value sounds good to me. What issues is that causing? Can you show some code?
ugly-tan•3y ago
there is no real need to set the first element as selected - you can derive that information if nothing has been selected:
value is what you pass to your dropdownlike-goldOP•3y ago
Thank you so much!