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.