I'm trying to learn how to use TanStack with TS, but I have various problems, I'm trying to execute this line of code, to obtain the data out of an API.
const { isLoading, isError, data, isFetching, refetch } =
useInfiniteQuery<ResultUsers>({
queryKey: ['users'],
queryFn: fetchUsers as any,
initialPageParam: 1,
getNextPageParam: (lastPage) => lastPage.nextCursor,
});
console.log(isFetching);
console.log(data);
isFetching always returns True, and data is always undefined. I don't know what is the problem.
This is my fetching function.
interface Props {
pageParam?: number;
}
export async function fetchUsers({ pageParam }: Props) {
const seed = 'horse'; // Random seed.
const apiLink = `https://XXXX.XX/api/?results=10&inc=email,picture,name,location&seed=${seed}&page=${pageParam}`;
return await fetch(apiLink)
.then((response) => {
if (!response.ok) throw new Error('Error when connecting to DB');
return response.json();
})
.then((data) => {
const resultUsers = data.results.map(
({ email, picture, name, location }: Result) => {
return {
id: email,
picture: picture.thumbnail,
firstName: name.first,
lastName: name.last,
country: location.country,
};
}
);
const resultPage = Number(data.info.page);
return { resultUsers, resultPage };
});
}
I have tried different solutions from different posts but I cant get it to work.