-
-
Save musaghauri/3b31d737fc2afe65cd9643dcefcde33b to your computer and use it in GitHub Desktop.
React Auth App - Profile
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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