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:
- When your request this page directly,
getServerSideProps
runs on server-side and fetchs articles. But on client-side,fetchData
in theuseEffects
would also run to fech the same articles again, which is redundant and a bit duplicated. - 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 rungetServerSideProps
on server-side, the other is sent byfetchData
. 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 ?