Skip to content

Instantly share code, notes, and snippets.

@RajithaKumara
Created April 23, 2019 11:24
Show Gist options
  • Save RajithaKumara/e84e9029abed513c403624e37dffc181 to your computer and use it in GitHub Desktop.
Save RajithaKumara/e84e9029abed513c403624e37dffc181 to your computer and use it in GitHub Desktop.
Access Node.js global varibale from Next.js page
'use strict';
let globalVar = null;
module.exports.get = function () {
return globalVar;
};
module.exports.set = function (v) {
globalVar = v;
};
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