sonlexqt
sonlexqt

Reputation: 6469

FlowRouter is not recognized inside of an apollo (graphql) query

I’m having a problem when using react-apollo with FlowRouter (in a meteor project). This is my graphql query (it is supposed to update each 5 seconds):

@graphql(myQuery, {
  options: {
    pollInterval: 5000,
    variables: {
      userId: FlowRouter.getQueryParam('r'),
      registerToken: FlowRouter.getQueryParam('registerToken')
    }
  },
})
export const default class MyComponent;

If I hard-coding the userId and registerToken arguments, the query works just fine.
So I guess the problem here is that these FlowRouter.getQueryParam() functions return undefined (even though I'm on client side). They work well if I call them inside of MyComponent or the browser console.

Upvotes: 1

Views: 60

Answers (2)

sonlexqt
sonlexqt

Reputation: 6469

Based on Loren's answer, I omitted the FlowRouter.getQueryParam() functions and used pure JavaScript instead (copied from this SO question):

function getParameterByName(name, url) {
    if (!url) {
      url = window.location.href;
    }
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

Usage:

// query string: ?foo=lorem&bar=&baz
var foo = getParameterByName('foo'); // "lorem"
var bar = getParameterByName('bar'); // "" (present with empty value)
var baz = getParameterByName('baz'); // "" (present with no value)
var qux = getParameterByName('qux'); // null (absent)

Everything's working now !

Upvotes: 0

Loren
Loren

Reputation: 14886

Is this code running on page load? I don't see why, but maybe getQueryParam is always undefined on page load? (Or you could parse location.href)

If so, it's reactive, so you could wait until it has a value, and then start the query:

Tracker.autorun(c =>
  if (FlowRouter.getQueryParam('r')) {
    // do query
    c.stop()
  }
)

Upvotes: 1

Related Questions