I'm in the process of setting up useInfiniteQuery to fetch jobs from the Github Jobs API. I have yet to set up the actual infinite query with a load more button, but right now I want to understand how can I reset the information from data that useInfiniteQuery returns and make a new query with new parameters, which I'm currently using as a state that gets set with react-hook-forms.
const [page, setPage] = useState(1);
const [searchParams, setSearchParams] = useState({
text: '',
location: '',
fullTime: false
});
const fetchJobs = async (key, page = 1) => {
const { text, location, fullTime } = searchParams;
try {
const res = await fetch(
`https://api.allorigins.win/get?url=${encodeURIComponent(
`https://jobs.github.com/positions.json?description=${text}&page=${page}&location=${location}&full_time=${fullTime}`
)}`
);
const json = await res.json();
const results = JSON.parse(await json.contents);
return {
results,
nextPage: page + 1
};
} catch (error) {
console.log(error);
}
};
const {status, data, error, isFetching, isFetchingMore, fetchMore, canFetchMore
} = useInfiniteQuery('jobs', fetchJobs, {
getFetchMore: (lastGroup, allGroups) => lastGroup.nextPage
});
const onSubmit = async data => {
const { text, location, fullTime } = data;
setSearchParams({
text,
location,
fullTime
});
// Want to make a new query call to fetch new Jobs with different parameters
// Using refetchOnWindowFocus uses the parameters from the new searchParams state,
// but using useQueryCache.refetchQueries() here does not, neither does
// expecting fetchJobs to get the updated state, as fetchJobs seems to always use the
// initial searchParams state
};
return (
<>
<Search onSubmit={handleSubmit(onSubmit)} ref={register} />
{isFetching && <p>Loading...</p>}
{data && <p>Got data</p>}
</>
);
As commented, when I try to just submit the form, the the state updates, but fetchJobs never gets the updated state.
Any help would be appreciated.
You need to pass in any data that may update as part of the query params in array form as the key. Or a deep equal as the deps on form data.
const {status, data, error, isFetching, isFetchingMore, fetchMore, canFetchMore
} = useInfiniteQuery(['jobs', text, location, fullTime], fetchJobs, {
getFetchMore: (lastGroup, allGroups) => lastGroup.nextPage
});
Link for more info https://react-query.tanstack.com/guides/query-functions
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