3

My folder structure looks like this:

/ pages
    / [project_id]
        / index.jsx    <- make this (or another external component) call an action before other pages will load
        / assets.jsx
        / information.jsx
        / ...

Before I'm accessing the rest of the files, i need a prefetched data saved in a redux state, which needs to be done before any page accessing it loads. The problem being, is that it requires me to add a useEffect hook inside each and every file to load the information i need.

Is there a way to "wrap" these pages with a single action call?

Artemixx
  • 97
  • 5

2 Answers2

0

You can make a wrapper component for the data fetching, and later wrap every page in that Layout component where you need to access the data.

First create the wrapper component

// components/Layout.jsx

const Layout = ({ children }) => {

  useEffect(() => {
    // fetch the data here and store it in redux state
  }, []);

  return (
    <>
      {children}
    </>
  );
};

export default Layout;

Then you can use this Layout component in your pages like this

// pages/[project_id]/index.jsx

import Layout from "../../components/Layout.jsx"

const Index = () => {
  // you can access data stored in redux store here
  const { data } = useSelector(state => state.data)

  return (
    <Layout>
     // your page's code goes here
    </Layout>
  );
};
binoy638
  • 139
  • 1
  • 6
  • This will be useful only in _app.js where it acts like a middleware and allowes **any** page to be rendered as child in this component. I'm talking about the same behavior on another page tree above _app.js, is it possible in next.js? – Artemixx Jul 20 '22 at 11:47
  • Sorry, I might have misunderstood your question, but as far as I know in next.js the _app.jsx renders first and all the pages are rendered as it's child component. – binoy638 Jul 20 '22 at 11:56
0

You can put your useEffect in _app.js. It will run only once as _app.js is not unmounted upon client side page navigation. And _app.js will run whenever you access any page.

If you need to prefetch the data server side, then it becomes a bit more complex and is hardly achieved without getInitialProps which Next.js wants to deprecate.

Viacheslav Luschinskiy
  • 1,309
  • 1
  • 10
  • 8