Using getServerSideProps and useEffect in Next.js to fetch data causes duplicate requests

Viewed 1698

I use getServerSideProps to fetch the initial articles data like this:

export const getServerSideProps = async () => {
  const url =
    "https://conduit.productionready.io/api/articles?limit=10&offset=0";
  const res = await fetch(url);
  const resJson = await res.json();

  return {
    props: {
      data: resJson.articles
    }
  };
};

I need to update articles when page change,so I have the codes below:

export default function IndexPage(props) {
  const { data } = props;
  const [articles, setArticles] = useState(data);
  const [page, setPage] = useState(0);

  useEffect(() => {
    const fetchData = async (page) => {
      const url = `https://conduit.productionready.io/api/articles?limit=10&offset=${page}`;
      const res = await fetch(url);
      const resJson = await res.json();
      setArticles(resJson.articles);
    };

    fetchData(page);
  }, [page]);

  //....
}

Then the question comes:

  1. When your request this page directly, getServerSideProps runs on server-side and fetchs articles. But on client-side, fetchData in the useEffects would also run to fech the same articles again, which is redundant and a bit duplicated.
  2. When transition to the IndexPage from another page through client-side route, there are also two requests for the same articles data: one request is sent to run getServerSideProps on server-side, the other is sent by fetchData. Again, redundant request for same data.

The complete demo is here

I think this is not an unusual situtation. I have seached a lot, but unfortunately, I haven't found any appropriate solutions. Does anyone encounter the same situation or know the best practice to handle it ?

0 Answers
Related