React and Sessions not working together

It is a very simple app with only 2 files : main.html and main.jsx.

main.html

<head>
  <title>session</title>
</head>

<body>
  <div id="root"></div>
</body>

main.jsx

import React, {Component} from 'react';

import {render} from 'react-dom';

import {Meteor} from 'meteor/meteor';


class App extends Component {
  method(){
    Session.set('name', 'Roger');
  }
  render(){
    return (<div>
      <h1>{Session.get('name')}</h1>
      <button onClick={this.method}>Set session</button>
    </div>)
  }
}

Meteor.startup(() => {
  render(<App/>, document.getElementById('root'))
})

Why it is not working?I mean clicking button shout print the “Roger”.
Please take not that I have added session before using meteor add session

I’m guessing that you’re trying to set an application wide variable, available to all components which need it.

In that case you really should think about using Redux (or similar). I guess it could also work by using the react-meteor-data package - but that’s actually intended for coupling React to Collections only.

Explanation for why your example does not work: React watches the state and decides whether to re-render components or not on changes to the state. Your Session variable lives outside the state and is thusly effectively invisible to React.

1 Like

You should put a setState inside a Tracker.autorun so it can be reactive.

Having this same issue, where would you put the Tacker.autorun? I’ve tried it everywhere and no luck.

You should use withTracker. Read more here: https://guide.meteor.com/react.html