Meteor.user() undefined in Meteor.startup() callback

Version : 1.3.1
ui: react

After logging in, if you refresh the page, the Meteor.user() sometimes returns undefined, it’s a very difficult issue to test because of how intermittent it is. My suspicion is that this is happening because there must be some background thread binding the currentUser and other data, which causes inconsistent behavior in the ui thread.

This becomes very apparent when using react-router with onEnter verification function checking if the user is logged in. See code sample:

//snippet from main.jsx
Meteor.startup(() => {
		render(<App />, document.getElementById('render-target'));
});
//snippet from App.jsx
export default class App extends Component {
	
	render() {
		return (
			<Router history={browserHistory}>
				<Route path="/" component={Home} onEnter={requireAuth}/>
				<Route path="/login" component={Login} onEnter={requireNotAuthed}/>
			</Router>
		);
	}
}

function requireAuth(nextState, replace) {
	if (!Meteor.user()) {
		replace({
			pathname: '/login',
			state: { nextPathname: nextState.location.pathname }
		})
	}
}

function requireNotAuthed(nextState, replace) {
	if (Meteor.user()) {
		replace({
			pathname: '/',
		})
	}
}

Right now i made the following change to allow time for the data to load and so far it’s been working on localhost, but it’s a really bad hack and it is yet to be tested on a remotely hosted system:

Meteor.startup(() => {
	setTimeout(() => {
		render(<App />, document.getElementById('render-target'));
	}, 200)
});

https://github.com/kadirahq/fast-render will fix the issue.

1 Like

Verify login with Meteor.userId() instead, as it’s immediately available, whereas Meteor.user() takes time for the data to come down the wire.

2 Likes