1

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.

1 Answer 1

0

I bit late, but I faced the same issue. Instead of using isFetching, you can use the fetchStatus value to know what is happening.

const { fetchStatus, data, refetch } =
useInfiniteQuery<ResultUsers>({
  queryKey: ['users'],
  queryFn: fetchUsers as any,
  initialPageParam: 1,
  getNextPageParam: (lastPage) => lastPage.nextCursor,
});

console.log(fetchStatus === 'fetching');
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.