Created
April 23, 2019 11:24
-
-
Save RajithaKumara/e84e9029abed513c403624e37dffc181 to your computer and use it in GitHub Desktop.
Access Node.js global varibale from Next.js page
This file contains hidden or 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
'use strict'; | |
let globalVar = null; | |
module.exports.get = function () { | |
return globalVar; | |
}; | |
module.exports.set = function (v) { | |
globalVar = v; | |
}; |
This file contains hidden or 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
import React from 'react'; | |
import util from 'util'; | |
class Page extends React.Component { | |
static async getInitialProps({ req }) { | |
let globalState = require('./global_state'); | |
if (globalState.get() === null) { | |
globalState.set(["Initial element"]); | |
console.log(globalState.get()); | |
} else { | |
let array = globalState.get(); | |
array.push(new Date()); | |
globalState.set(array); | |
console.log(globalState.get()); | |
} | |
return { globalVar: globalState.get() }; | |
} | |
render() { | |
const { globalVar } = this.props; | |
return ( | |
<div> | |
{util.inspect(globalVar)} | |
</div> | |
); | |
} | |
} | |
export default Page; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment