TanStackT
TanStack2y ago
3 replies
wet-aqua

"Lazy Query" dependent on an event occurrence - best approach?

Hey there.

My problem is quite simple, but I struggle to find a good approach.

The case looks like this:
- user opens context menu (with right-click); ContextMenu is a separate component and is lying within the main App component;
- within the context menu, there is an option - clicking on that option should result in the following sequence:

1) fetch data, dependent on the option clicked (see it as a filter, I was trying to use Zustand state management to pass the filter value);
2) on response, either do nothing at all (at the current point, no error, etc is needed to be handled) or execute a function that should use the response data to update the current state (a global one, handled by Zustand);

I was trying different ways, but didn't end up with something that works perfectly. I need the query to execute once, when the filter value changes. Was trying to build custom hooks, but was running into different problems like infinite loops, extra re-renders, etc.

If I would not use React Query, the raw solution in simple terms might be something like:

useEffect(() => { if (filter === 'none') return if (filter === 'all') fetchData(data) .then((newData) => { setData(doSomethingWithNewData(newData)) setFilter('none') }) .catch(() => setfilter('none')) //etc }, [filter])

filter would be handled by Zustand so I could just update that on the context menu item click and the
useEffect
should react whenever it is.

Also most of the stuff is async, so that should be respected too.

Thanks in advance! I'm happy to provide more information if this wouldn't be enough or is not clear.
Was this page helpful?