2

I have several pages that require auth in my next.js app. Here's an example:

const Home: NextPage = () => {
  const currUser = useAppSelector(state => state.auth);
  return (
    <div className="space-y-3">
      {currUser.loggedIn ? (
            <p>logged in</p>
        ))
      ) : (
        <p>not logged in</p>
      )}
    </div>
  );
}

I thought at first I can put logic into _app.tsx in a similar way as I did with the page above to detect which component I display based on if redux has login state for the user. the problem is useAppSelector is from redux, and _app.jsx doesn't have access to it as the Provider component wraps it with the store as can be seen here:

function MyApp({ Component, pageProps }: AppProps) {
  const currUser = useAppSelector(state => state.auth); // NOT POSSIBLE, no provider yet

  return (
    <Provider store={store}>
          <Layout>
            <Component {...pageProps} />
          </Layout>
    </Provider>
  );
}

What's a design pattern I can use to protect components with state from redux (reduxjs-toolkit in this case) if I can't do it directly in _app.tsx?

randombits
  • 47,058
  • 76
  • 251
  • 433
  • 1
    You already have access to "store" in this component. But most times you'll need it in layout comps like header, where redux context is already provided. It's unclear what's the use for it in app file – Estus Flask Sep 11 '22 at 22:46
  • I don't need it in the header for this app. I just need to display content A if user is logged in or content B if they aren't. That content isn't in the header. Not exactly sure how to retrieve state from `store` in this particular case. – randombits Sep 11 '22 at 22:57
  • See https://stackoverflow.com/questions/38332912/how-do-i-access-store-state-in-react-redux . You may have XY problem. It's unclear where `store` comes from in app file and how auth is supposed to work in your case. Can't be just imported. There may be natural problems in Next with global state because it needs to be separate for each user, and server-side code is executed for many users simultaneously, so their global state is mixed up. It can be something like https://blog.logrocket.com/use-redux-next-js/ . Notice that auth check happens in Next getServerSideProps hook in this example – Estus Flask Sep 12 '22 at 04:34

0 Answers0