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
?