-
Hi, I have a simple app where I load data according to two datepickers ( I would like to be able to make the requests on the datepicker change event, but using the same key so the component doesn't suspend because of the empty data / lack of cache for the new URL. Here is basically what it looks like: function getTasks({ queryKey }) {
const [, { options }] = queryKey;
return axios(`/tasks?${qs.stringify(options)}`);
}
function useTasks(from, to) {
const options = useMemo(() => ({ from, to }), [from, to]);
return useQuery(['tasks', { options }], getTasks, { suspense: true });
}
function MyComponent({ from, to }) {
const { data } = useTasks(from, to); // problem here, when from or to changes, the key changes and the component suspends
return (
<ul>
{data.map(({ id, name }) => <li key={id}>{name}</li>}
</ul>
);
} I tried a version where function getTasks(options) {
return () => axios(`/tasks?${qs.stringify(options)}`);
}
function useTasks(from, to) {
const options = useMemo(() => ({ from, to }), [from, to]);
return useQuery(['tasks'], getTasks(options), { suspense: true });
} Can you enlighten me here to help me understand what's happening and what would be the right way to achieve that? Thank you very much! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
you can set |
Beta Was this translation helpful? Give feedback.
you can set
keepPreviousData: true
to show the data from the previous query key when the key changes. You'll also getisPreviousData: true
returned while the previous data is rendered. That way, you won't get a hard loading state, so no suspense, and you can still stick to keeping all the dependencies (from & to) in the query key.