DEV Community

Sh Raj
Sh Raj

Posted on • Updated on

NextJS loading problem 🀨 - refetching api data on revisit #64822

Summary

if i click and navigate to about from the main page after loading of data in main page and then i come from about to the main page using navigation i see the loading once or req too the api is sent once more time, I don't want that if the user already loaded the api and navigated then come back it should show the previous data ( even it should show the scroll loc until I scrolled on the main page)


"When a user navigates from the main page to the about page after the data has loaded on the main page, and then returns to the main page using navigation, I want to ensure that the data isn't reloaded unnecessarily. I want the previously fetched data to be displayed without triggering another API request. Additionally, I'd like the scroll position of the main page to remain unchanged, even after navigating away from and back to the main page."

https://github.com/SH20RAJ/nextjs-loading-problem/assets/66713844/63a0b094-35c7-4c54-9c10-126feefd4cc7

See like youtube is also a single page app and fetches the video feeds from api (client side). but when we navigate to another page then come back we see the previous video feeds but in my case if I come back to my page it recalls the api fetch and show the data (only in case of client component )

Test and open preview on Stackblitz :- https://stackblitz.com/~/github.com/SH20RAJ/nextjs-loading-problem
Github Repo :- https://github.com/SH20RAJ/nextjs-loading-problem

Specific Commit :- https://github.com/SH20RAJ/nextjs-loading-problem/tree/84f8788a05479c63cd8737a9d5a340a31aabf69e

// Used Suspense
// Used loading state from useState()
// Used Loading.js

// Still the problem isn't solved yet

// have to do it in client side because server side is working

Additional information

// Used Suspense
// Used loading state from useState()
// Used Loading.js

// Still the problem isn't solved yet


// have to do it in client side because server side is working
Enter fullscreen mode Exit fullscreen mode

Example

https://stackblitz.com/~/github.com/SH20RAJ/nextjs-loading-problem


Answer this is comments or https://github.com/vercel/next.js/discussions/64822


I got the answer using swr and here I made a video on it :-

Top comments (1)

Collapse
 
sh20raj profile image
Sh Raj

To achieve client-side data caching in a Next.js app using the App Router, follow these steps to ensure that data fetched on the client side is preserved when navigating away and returning to the page.

  1. Set Up Context for Data Storage:
    Create a context to hold your data globally across the app.

  2. Store and Retrieve Data:
    Save the fetched data in the context and check for this data before making a new fetch request.

Here's an example implementation:

// context/DataContext.js
import { createContext, useContext, useState } from 'react';

const DataContext = createContext();

export const DataProvider = ({ children }) => {
  const [data, setData] = useState(null);

  return (
    <DataContext.Provider value={{ data, setData }}>
      {children}
    </DataContext.Provider>
  );
};

export const useDataContext = () => useContext(DataContext);
Enter fullscreen mode Exit fullscreen mode
// app/layout.js
import { DataProvider } from '../context/DataContext';

export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        <DataProvider>
          {children}
        </DataProvider>
      </body>
    </html>
  );
}
Enter fullscreen mode Exit fullscreen mode
// app/page.js
import { useEffect } from 'react';
import { useDataContext } from '../context/DataContext';

export default function HomePage() {
  const { data, setData } = useDataContext();

  useEffect(() => {
    if (!data) {
      fetchData();
    }
  }, [data]);

  const fetchData = async () => {
    const response = await fetch('/api/data');
    const result = await response.json();
    setData(result);
  };

  return (
    <div>
      {data ? (
        <pre>{JSON.stringify(data, null, 2)}</pre>
      ) : (
        <p>Loading...</p>
      )}
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

This approach ensures that data fetched from the API is cached on the client side and reused when navigating back to the page, preventing unnecessary refetches.