In web development, providing a seamless and user-friendly experience is crucial. One common scenario involves loading a list of blog posts and allowing users to fetch more posts with a "Load More" button. However, when users click on a blog post and then navigate back, the page often resets, and users lose their loaded content. In this blog post, we'll explore how to overcome this challenge by leveraging the power of sessionStorage
in a Next.js application.
When building dynamic pages in Next.js, it's essential to consider user interactions, especially when implementing features like paginated blog lists. By default, when users click on a blog post and then navigate back, the page resets to its initial state. To enhance this experience, we'll use sessionStorage
to store and retrieve the blog list, along with other relevant state variables.
Firstly, we'll use the useEffect
hook to check whether there is data stored in sessionStorage
when the component mounts. If data is found, we'll use it to set the initial state. This ensures that users see the previously loaded blog list even after navigating away from the page.
useEffect(() => {
const storedList = JSON.parse(sessionStorage.getItem("postList"));
const storedShowLoadMore = sessionStorage.getItem("showLoadMore");
const storedPageId = sessionStorage.getItem("pageId");
setList(storedList || props.posts);
setShowLoadMore(storedShowLoadMore === "true" || props.showLoadMore);
if (storedPageId) setPageId(storedPageId);
}, [props.posts, props.showLoadMore]);
Next, we'll modify the fetchList
function to not only update the local state but also save the latest data to sessionStorage
. This ensures that the current state is preserved, allowing users to see the complete page even after navigating away and returning.
const fetchList = async (pageId) => {
setIsError(false);
setIsLoading(true);
try {
const result = await getPublicPosts(pageId);
const newList = list.concat(result.data);
if (result.total > newList.length) {
setShowLoadMore(true);
} else {
setShowLoadMore(false);
}
setList(newList);
// Save data to sessionStorage
sessionStorage.setItem("postList", JSON.stringify(newList));
sessionStorage.setItem("showLoadMore", showLoadMore);
sessionStorage.setItem("pageId", pageId);
} catch (err) {
setIsError(true);
}
setIsLoading(false);
};
By incorporating sessionStorage
into our Next.js application, we've addressed the common issue of losing loaded content when users navigate back from a blog post. This approach ensures that users can seamlessly continue browsing the blog list without interruptions. While more advanced state management tools like Redux might be unnecessary in this case, sessionStorage
proves to be a simple yet effective solution for preserving state in a Next.js application. Consider implementing this technique in your projects to create a smoother and more enjoyable user experience.