How to refresh promise which depends on multiple variables
ApoorvGuptaAi opened this issue · comments
Raising an issue since I dont see clear documentation on this.
** Use case:
Given the following data in a component
const {data1, data2} = useCustomHook();
I need to run an async function getAsyncData(arg1, arg2)
(which takes as arguments arg1=data1.id and arg2=data2.id) everytime data1 or data2 changes.
What i have come up with:
const memoizedAsync = useMemo(() => getAsyncData(data1.id, data2.id)), [data1, data2]);
const {data, isPending} = useAsync({promise: memoizedAsync});
Seems like there is a concept of promiseFn and watch values, which seems like they can do this in a more concise way, but couldnt find good documentation on what that would look like. (Another bug(#254) talks about how arrays cant be used in the watch value, so having a recommended solution would be good).
For a proposal on my current project, I ended up going with something like this:
const memoizedRequestParams = useMemo(() => {
return {
pageNumber: page,
pageSize: 20,
sortColumn,
sortAscending,
};
}, [page, sortColumn, sortAscending]);
const {
data,
isPending,
} = useAsync(getData, {
watch: memoizedRequestParams,
...memoizedRequestParams,
});
Not sure if that's better, but definitely another approach that works. I agree though that it would be nice to get some documentation on this kind of use case, because I have to imagine it's fairly common.
@Josh-Marston-1005 that's a pretty good approach 👍 I think useMemo should be the recommended way.
@ghengeveld Awesome, thanks man. Really helps me validate my thinking there, and thanks for making such a useful library for handling this kind of flow 👍
@Josh-Marston-1005 @ghengeveld Thanks for your comments.
I do prefer what Josh proposed (as long as typescript is fine with it, not sure if this looks type safe).
Gert, I can send out a PR updating the .md files (maybe something called watching.md), does that seem fine to you?
@ApoorvGuptaAi Yes that would be great. Let's add a chapter in the Guide about "Watching for changes". It should come after Async Actions and before Optimistic Updates (in _summary.md
). Please draft it up, it doesn't have to be perfect. I'll review and probably add some narrative around it.