I'm currently working on a project which uses some shared JS between client and server. The tech stack includes Node v6, Webpack, React etc.
There's a directory "shared" from which server and client require a file called rules.js. On the first render which happens on the server side, the rules variable declared in rules.js is set with a value from DB (I've done console.log to verify it's really filled with data).
Then on client side some component might require this rules.js file and get the rules variable. However, when I console.log the variable, it's empty.
The rules file looks similar to this:
// shared/rules.js
let rules;
// This is called on server to set the value
exports.setData = function(data) {
rules = data;
}
exports.rules = rules;
Do you have any idea what could be wrong? Should I choose different approach?
While the file may be shared by both the client and server, the instance of the class is not. So, anything you do to it on the server will not persist on the client, and vice versa.
One idea available is that of "dehydrating" and "rehydrating" your state.
server.js
// implemented in server to dehydrate your state
import rules from '../shared/rules';
let dehydratedRules = JSON.stringify(rules.rules);
let html = renderToString(<App/>);
// now in your render call
res.render('yourTemplateFile', {html, dehydratedRules});
yourTemplateFile
...
<script type="text/javascript">var __RULES__ = {{dehydratedRules}};
...
client.js
// implemented in client to rehydrate your state
import rules from '../shared/rules';
let parsedRules = JSON.parse(__RULES__);
delete window.__RULES__;
// set the rehydrated data back in the class
rules.setData(parsedRules);