Skip to content

Instantly share code, notes, and snippets.

@musaghauri
Last active January 16, 2018 11:56
Show Gist options
  • Save musaghauri/3b31d737fc2afe65cd9643dcefcde33b to your computer and use it in GitHub Desktop.
Save musaghauri/3b31d737fc2afe65cd9643dcefcde33b to your computer and use it in GitHub Desktop.
React Auth App - Profile
//Frontend call for fetching profile
async componentWillMount() {
const token = cookies.load('token');
if(!token) Router.push("/");
else if (!this.props.isServer){
this.setState({ loading: true });
const token = cookies.load('token');
const requestURL = `/api/profile`;
const options = createRequestOptions('GET', null, { Authorization: `Bearer ${token}` });
const requestObject = await fetch(requestURL, options);
const user = await requestObject.json();
this.setState({ user, loading: false });
}
}
// Serverside getInitialProps call for fetching profile in case JS is disabled
static async getInitialProps({ req }) {
const isServer = typeof window === 'undefined';
if(isServer) {
const baseUrl = req ? `${req.protocol}://${req.get('Host')}` : '';
const token = req.cookies.token;
const requestURL = `${baseUrl}/api/profile`;
const options = createRequestOptions('GET', null, { Authorization: `Bearer ${token}` });
const requestObject = await fetch(requestURL, options);
const user = await requestObject.json();
return { user, isServer };
} else {
return { isServer }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment