0

I am new to react-query and I am having some trouble implementing the useInfiniteQuery function. I've tried implementing it into my website, however it doesn't seem to increment the pageIndex variable as it should. The pageIndex remains at 0 all the time, hence duplicating my posts every time I'm fetching the data. The offset variable is used for my database to get the n row from where the query is to be fetched.

Looking for help, thanks.

Here is the front-end part:

import React from "react";
import { useRef, useCallback} from "react";
import axios from "axios";
import { Link } from "react-router-dom";
import { useInfiniteQuery } from "react-query";

const PAGE_LIMIT = 10;

const fetchPosts = async (key, pageIndex = 0) => {
  const offset = pageIndex * PAGE_LIMIT;
  try {
    const { data } = await axios.get(`/posts`, {
      params: { offset: offset, limit: PAGE_LIMIT },
    });
    return data;
  } catch (err) {
    console.log(err);
  }
};

const Home = () => {
  const {
    fetchNextPage,
    hasNextPage, 
    isFetchingNextPage, 
    data,
    status,
    error,
  } = useInfiniteQuery("/posts", ({ pageIndex = 0 }) => fetchPosts(pageIndex), {
    getNextPageParam: (lastPage, allPages) => {
      return lastPage.length ? allPages.length : undefined;
    },
  });

  const intObserver = useRef();
  const lastPostRef = useCallback(
    (post) => {
      if (isFetchingNextPage) return;

      if (intObserver.current) intObserver.current.disconnect();

      intObserver.current = new IntersectionObserver((posts) => {
        if (posts[0].isIntersecting && hasNextPage) {
          console.log("We are near the last post!");
          fetchNextPage();
        }
      });

      if (post) intObserver.current.observe(post);
    },
    [isFetchingNextPage, fetchNextPage, hasNextPage]
  );

  if (status === "error")
    return <p className="center">Error: {error.message}</p>;

  const content = data?.pages.map((pg) => {
    return pg.map((post, i) => {
      if (pg.length === i + 1) {
        return (
          <Link ref={lastPostRef} className="link" to={`/post/${post.id}`}>
            <div className="post" key={post.id}>
              <p> {post.title}</p>
              <p> {post.content}</p>
            </div>
          </Link>
        );
      }
      return (
        <Link className="link" to={`/post/${post.id}`}>
          <div className="post" key={post.id}>
            <p> {post.title}</p>
            <p> {post.content}</p>
          </div>
        </Link>
      );
    });
  });

  return (
    <div>
      <div className="home">
        <div className="container">
          <div className="posts">
            {content}
            {isFetchingNextPage && (
              <p className="center">Loading More Posts...</p>
            )}
            <p className="center">
              <a href="#top">Back to Top</a>
            </p>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Home;

Here is the back-end part:

import { db } from "../db.js";

export const getPosts = (req, res) => {
  const { offset, limit } = req.query;
  console.log(`Offset is ${offset}`);
  const q = `SELECT * FROM test1 ORDER BY ID LIMIT ?, ?`;

  db.query(q, [parseInt(offset), parseInt(limit)], (err, data) => {
    if (err) return res.status(500).json(err);

    return res.status(200).json(data);
  });
};

1 Answer 1

1

The fetch callback you give useInfiniteQuery receives a QueryFunctionContext. It has a property called pageParam. You use pageIndex which is not on that object. Because you give it a default value of 0 it will just always be zero. Use pageParam instead.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, it was an easy fix once I know where I need to look. I've removed the key variable from the fetchPosts() function as well which gave a bit of a headache.

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.