Apollo Cache not updating when changing Query variables

Viewed 536

I'm following this tutorial https://www.howtographql.com/react-apollo/0-introduction/ and I discovered an issue.

I have a component named LinkLists which displays a list of links and it's paginated.

import React, { useEffect } from "react";
import Link from "./Link";
import { useQuery } from "@apollo/client";
import { useNavigate } from "react-router-dom";
import { LINKS_PER_PAGE } from "../utilities/constants";
import FEED_QUERY from "../graphql/queries/feedLinks";
import NEW_LINKS_SUBSCRIPTION from "../graphql/subscriptions/newLinks";
import NEW_VOTES_SUBSCRIPTION from "../graphql/subscriptions/newVotes";
import getQueryVariables from "../utilities/getQueryVariables";
import getLinksToRender from "../utilities/getLinksToRender";

const LinkList = () => {
  const navigate = useNavigate();
  const isNewPage = window.location.pathname.includes("new");
  const pageIndexParams = window.location.pathname.split("/");
  const page = parseInt(pageIndexParams[pageIndexParams.length - 1]);

  const pageIndex = page ? (page - 1) * LINKS_PER_PAGE : 0;

  const { data, loading, error} = useQuery(FEED_QUERY, {
    variables: getQueryVariables(isNewPage, page),
  });

  return (
    <>
      {loading && <p>Loading...</p>}
      {error && <pre>{JSON.stringify(error, null, 2)}</pre>}
      {data && (
        <>
          {getLinksToRender(isNewPage, data).map((link, index) => (
            <Link key={link.id} link={link} index={index + pageIndex} />
          ))}
          {isNewPage && (
            <div className="flex ml4 mv3 gray">
              <div
                className="pointer mr2"
                onClick={() => {
                  if (page > 1) {
                    navigate(`/new/${page - 1}`);
                  }
                }}
              >
                Previous
              </div>
              <div
                className="pointer"
                onClick={() => {
                  if (page < data.feed.count / LINKS_PER_PAGE) {
                    const nextPage = page + 1;
                    navigate(`/new/${nextPage}`);
                  }
                }}
              >
                Next
              </div>
            </div>
          )}
        </>
      )}
    </>
  );
};

export default LinkList;

When next is clicked, it navigates to the next page and renders the next set of links correctly. But after the links are loaded and I try to go to a previous page with new variables, the data is not being updated. I get the recent data but on a different page which is supposed to render older data. I think it has to do something with the cache but I'm not really sure. I'm still learning about Apollo Client and I'm not sure what is going wrong especially that I followed a tutorial.

0 Answers
Related