Reputation: 103
I decided to use React's ContextAPI to store authenticated user data.
I've implemented a custom App component and wrote a getInitialProps
function to retrieve user's data from the backend.
class MyApp extends App {
render() {
const { Component, pageProps, authenticated, user } = this.props;
return (
<AuthProvider authenticated={authenticated}>
<UserProvider userData={user}>
<Component {...pageProps} />
</UserProvider>
</AuthProvider>
);
}
}
MyApp.getInitialProps = async (appContext) => {
let authenticated = false;
let user = null
const request = appContext.ctx.req;
if (request) {
request.cookies = cookie.parse(request.headers.cookie || '');
authenticated = !!request.cookies.sessionid;
if (authenticated){
user = await getCurrentUserData(request.headers.cookie)
}
}
// Call the page's `getInitialProps` and fill `appProps.pageProps`
const appProps = await App.getInitialProps(appContext);
return { ...appProps, authenticated, user };
};
export default MyApp;
What's concerns me the most is that getCurrentUserData
is called every time a page is being rendered, so there is always one extra API call.
Is it good practice to do so? Should I store user's data in a cookie, and update context from there? How can I optimize this solution?
Thanks
Upvotes: 2
Views: 1115
Reputation: 476
If you don't want it to be called for every page. You can create HoC for the Auth.. and use this HoC only for the page that use the user data.
usually the page that don't need user data is static page which is quite situational most of the time.
Upvotes: 0