Is it possible to access state within withtracker?

Is it possible to access react state within withtracker? It doesnt seem to work for me, is it possible to make it work?

export default AppBar = withTracker(() => {
var handles = [
Meteor.subscribe(‘options’),
Meteor.subscribe(‘selection’),
];
const loading = !handles.every(handle => handle.ready());
const optionsReady = (loading && this.state.selection);
return {
loading,
games: loading ? null : Selections.find(),
draws: loading ? null : Options.find({selectionId: this.state.selection._id}),
};
})(AppBar);;

If you’re wrapping a React component in a higher-order component, the higher-order component is a “wrapper” that has access to stuff that comes in from the outside (props) but cannot access stuff on the inside (state). It’s a layer that sits between the parent component and the component being wrapped! So, no, I’m afraid you can’t literally access wrapped component state from the HoC (whether it’s withTracker or any other HoC).

However, you always “lift” the state out to a higher level. For example, you could wrap the withTracker-wrapped component with something stateful that you would be able to access (even if it’s as simple as a functional component with a state hook), or move your state somewhere else like Redux that isn’t tied to the component hierarchy.

I’ve been using reactive vars, or reactive dicts for this.

export const Selection = new ReactiveVar({});
export default AppBar = withTracker(() => {
  var handles = [
    Meteor.subscribe(‘options’),
    Meteor.subscribe(‘selection’),
  ];
  const loading = !handles.every(handle => handle.ready());
  const selection = Selection.get();
  const optionsReady = (loading && selection);
  return {
    loading,
    games: loading ? null : Selections.find(),
    draws: loading ? null : Options.find({selectionId: selection._id}),
  };
})(AppBar);

Except I’d place Selection in a separate file, something like /imports/ui/state.js, or /imports/ui/state/appbar.js, then import it in the container and the AppBar to use it.

1 Like

This worked easy enough. Thanks!