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

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.

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()
}
)

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 !

Related

How to assign snap.val() to the global variable?

I want to assign snap.val() to this.Productslike this.Products= snap.val(); but this.Products is undefined in that scope.
Products: FirebaseListObservable<any>;
constructor(){
}
ionViewDidLoad(){
this.angularFire.database.list('/Products').$ref.orderByChild('uid')
.equalTo('NW1Kq4WB7ReUz2BNknYWML9nF133').on('child_added', function(snap){
console.log(snap.val().name);
//this.Products= snap.val();
});
}
I tried the following code when snap is returned ,but I receive this message -- No index defined for uid:
snap.forEach(SnapShot=>{
console.log(SnapShot.val().name)
My Firebase database:
"Products" : {
"-Kbx0i-TFeTyRbNZAZ_8" : {
"category" : "1",
"detail" : "xxxxx details",
"name" : "xxxxx",
"uid" : "NW1Kq4WB7ReUz2BNknYWML9nF133"
}
Please help. Thanks.
The directly answer the question you asked, you can use an ES6 arrow function:
let query = this.angularFire.database.list('/Products').$ref.orderByChild('uid')
.equalTo('NW1Kq4WB7ReUz2BNknYWML9nF133');
query.on('child_added', (snap) => this.Products= snap.val());
Or for ES5 compatibility, declare this as a variable:
let self = this;
let query = this.angularFire.database.list('/Products').$ref.orderByChild('uid')
.equalTo('NW1Kq4WB7ReUz2BNknYWML9nF133');
query.on('child_added', function(snap) {
self.Products= snap.val();
});
But in reality, this is an XY problem and you don't want what you think you want here.
What you've done is reimplement the list yourself, and defeat the entire purpose of AngularFire2, which handles all this synchronization on your behalf.
Additionally, you've mis-used child_added by assigning each record you get back (you get an array of results, not exactly one) to this.products, when you probably wanted to set this.products = [] and then use this.products.push(snap.val()) for each child_added invocation.
So what you really want here, is to use AngularFire's built-in queries and avoid this entire mess :)
this.products = af.database.list('/Products', {
query: {
orderByChild: 'uid',
equalTo: 'NW1Kq4WB7ReUz2BNknYWML9nF133'
}
});
I did it in this way:
import firebase from "firebase";
const firebaseConfig = {
your firebaseConfig...
};
let app = firebase.initializeApp(firebaseConfig);
let database = firebase.database();
export async function readFromFirebase(userId, key) {
const ref = database.ref("users/" + userId + "/" + key);
const snapshot = await ref.once("value");
return snapshot.val();
}
async function main() {
console.log(await readFromFirebase(109512127, "userName"));
}
main();

Angular JS object scope

I have written a simple Angular JS code which greets user depending on the time of the day. It works fine. The code is given below:
var modSvc = angular.module("appName",[]);
modSvc.provider("date",function(){
var greeting;
return {
showGreeting:function(value){
greeting = value;
},
$get:function(){
//it has to return an object which can have variables and functions
return {
showDate:function(){
var date = new Date();
return date.getHours();
},
showGreetingMessage:function(){
//var date = new Date();
return greeting + ", It's "+ this.showDate();
}
}
}
};
});
modSvc.config(function(dateProvider){
var hours = dateProvider.$get().showDate();
if(hours<12)
dateProvider.showGreeting("Good morning!");
else if(hours<17)
dateProvider.showGreeting("Good afternoon!");
else if(hours<22)
dateProvider.showGreeting("Good evening!");
else
dateProvider.showGreeting("Good night!");
});
function serviceController($scope,date){
$scope.greetingMessage = date.showGreetingMessage();
}
modSvc.controller("svcController",serviceController);
If you see showGreetingMessage function it has only one line of code which is:
return greeting + ", It's "+ this.showDate();
However showDate function resides at the same level as that of showGreetingMessage function. That's why this.showDate should not work and it should give error. But it works perfectly fine. How is it so?
It depends on the JavaScript engine that is used but according to the Mozilla reference your "this" actually references the parent object since you are returning an object.
As an object method
When a function is called as a method of an object, its this is set to the object the method is called on.
In the following example, when o.f() is invoked, inside the function this is bound to the o object.
var o = {
prop: 37,
f: function() {
return this.prop;
}
};
console.log(o.f()); // logs 37

GET with query string with Fetch in React Native

I am making a request like this:
fetch("https://api.parse.com/1/users", {
method: "GET",
headers: headers,
body: body
})
How do I pass query string parameters? Do I simply add them to the URL? I couldn't find an example in the docs.
Your first thought was right: just add them to the URL.
Remember you can use template strings (backticks) to simplify putting variables into the query.
const data = {foo:1, bar:2};
fetch(`https://api.parse.com/1/users?foo=${encodeURIComponent(data.foo)}&bar=${encodeURIComponent(data.bar)}`, {
method: "GET",
headers: headers,
})
Short answer
Just substitute values into the URL like this:
const encodedValue = encodeURIComponent(someVariable);
fetch(`https://example.com/foo?bar=${encodedValue}`);
Longer answer
Yes, you just need to add the query string to the URL yourself. You should take care to escape your query string parameters, though - don't just construct a URL like
`https://example.com/foo?bar=${someVariable}`
unless you're confident that someVariable definitely doesn't contain any &, =, or other special characters.
If you were using fetch outside of React Native, you'd have the option of encoding query string parameters using URLSearchParams. However, React Native does not support URLSearchParams. Instead, use encodeURIComponent.
For example:
const encodedValue = encodeURIComponent(someVariable);
fetch(`https://example.com/foo?bar=${encodedValue}`);
If you want to serialise an object of keys and values into a query string, you could make a utility function to do that:
function objToQueryString(obj) {
const keyValuePairs = [];
for (const key in obj) {
keyValuePairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]));
}
return keyValuePairs.join('&');
}
... and use it like this:
const queryString = objToQueryString({
key1: 'somevalue',
key2: someVariable,
});
fetch(`https://example.com/foo?${queryString}`);
Here's an es6 approach
const getQueryString = (queries) => {
return Object.keys(queries).reduce((result, key) => {
return [...result, `${encodeURIComponent(key)}=${encodeURIComponent(queries[key])}`]
}, []).join('&');
};
Here we're taking in a queries object in the shape of key: param
We iterate and reduce through the keys of this object, building an array of encoded query strings.
Lastly we do a join and return this attachable query string.
I did a small riff on Mark Amery's answer that will pass Airbnb's eslint definitions since many teams seem to have that requirement these days.
function objToQueryString(obj) {
const keyValuePairs = [];
for (let i = 0; i < Object.keys(obj).length; i += 1) {
keyValuePairs.push(`${encodeURIComponent(Object.keys(obj)[i])}=${encodeURIComponent(Object.values(obj)[i])}`);
}
return keyValuePairs.join('&');
}
My simple function to handle this:
/**
* Get query string
*
* #param {*} query query object (any object that Object.entries() can handle)
* #returns {string} query string
*/
function querystring(query = {}) {
// get array of key value pairs ([[k1, v1], [k2, v2]])
const qs = Object.entries(query)
// filter pairs with undefined value
.filter(pair => pair[1] !== undefined)
// encode keys and values, remove the value if it is null, but leave the key
.map(pair => pair.filter(i => i !== null).map(encodeURIComponent).join('='))
.join('&');
return qs && '?' + qs;
}
querystring({one: '##$code', two: undefined, three: null, four: 100, 'fi###ve': 'text'});
// "?one=%23%40%24code&three&four=100&fi%23%23%40ve=text"
querystring({});
// ""
querystring('one')
// "?0=o&1=n&2=e"
querystring(['one', 2, null, undefined]);
// "?0=one&1=2&2" (edited)
Yes you should, there are a few classes in JS, that can help you a handy one is https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
e.g. if you had the params in a javascript object say
let params = {one: 'one', two: 'two'}
you could say this function
let queryString = new URLSearchParams()
for(let key in params){
if(!params.hasOwnkey())continue
queryString.append(key, params[key])
}
then you can get your nicely formatted query string by saying
queryString.toString()
The accepted answer works, but if you have more params than one it doesn't generalize. I suggest the following approach, which also handles array parameters:
let route = 'http://test.url.com/offices/search';
if (method == 'GET' && params) {
const query = Object.keys(params)
.map((k) => {
if (Array.isArray(params[k])) {
return params[k]
.map((val) => `${encodeURIComponent(k)}[]=${encodeURIComponent(val)}`)
.join('&');
}
return `${encodeURIComponent(k)}=${encodeURIComponent(params[k])}`;
})
.join('&');
route += `?${query}`;
}

How to extend returned objects in the list returned by $asArray?

I'm having trouble decorate the objects in my list returned by $asArray in angularfire with a new method (not decorating the array itself).
The angularfire documentation seems to suggest that the right way to do this is to override the $$added method in the factory for $FirebaseArray, returning a new object that either encapsulates or extends the snapshot that gets passed in to that method. From the documentation:
// an object to return in our JokeFactory
app.factory("Joke", function($firebaseUtils) {
function Joke(snapshot) {
this.$id = snapshot.name();
this.update(snapshot);
}
Joke.prototype = {
update: function(snapshot) {
// apply changes to this.data instead of directly on `this`
this.data = snapshot.val();
},
makeJoke: function() {
alert("Why did the " + this.animal + " cross the " + this.obstacle + "?");
},
toJSON: function() {
// since we didn't store our data directly on `this`, we need to return
// it in parsed format. We can use the util function to remove $ variables
// and get it ready to ship
return $firebaseUtils.toJSON(this.data);
}
};
return Joke;
});
app.factory("JokeFactory", function($FirebaseArray, Joke) {
return $FirebaseArray.$extendFactory({
// change the added behavior to return Joke objects
$$added: function(snap) {
return new Joke(snap);
},
// override the update behavior to call Joke.update()
$$updated: function(snap) {
this.$getRecord(snap.name()).update(snap);
}
});
});
However, when I do this in my code, nothing ever gets added to the array, although I can see from outputting to the console that it is getting called.
var printMessageObjConstructor = function(snap) {
this.$id = snap.name();
this.snapshot = snap;
this.$update = function(snap) {
this.snapshot = snap;
};
this.printMessage = function() {
return this.author + "'s question is: " + this.body;
};
};
var ref = new Firebase("https://danculley-test.firebaseio.com/questions");
//What Am I Doing Wrong Here?
var arrayFactory = $FirebaseArray.$extendFactory({
$$added: function(snap, prevChild) {
var x = new printMessageObjConstructor(snap);
console.log("I am being called from FirebaseDecoratedCtlOverloadAddedinNewObj.");
return x;
},
$createObject: function(snap) {
return new printMessageObjConstructor(snap);
},
$$updated: function(snap) {
var i = this.$indexFor(snap.name());
var q = this.$list[i];
q.$update(snap);
}
});
var sync = $firebase(ref, {arrayFactory:arrayFactory});
var list = sync.$asArray();
list.$loaded(function(list) {
$scope.questions = list;
});
I've set up a new plunk stripped down to show the issue with a couple other use cases that I've tried. (The actual method I'm adding is more complex and isn't related to the view, but I wanted to do something simple to reproduce the issue.)
I think the issue is that I don't quite understand what exactly $$added is supposed to return, or what additional behavior beside returning the value to be stored $$added is supposed to have. There also doesn't really seem to be an $$added on the prototype or on $FirebaseArray to call as a super to get the default behavior. Can someone point me in the right direction?
UPDATE
For the benefit of others, after reviewing the like that Kato posted, I was able to solve the issue by adding the following, almost all copied directly from the source except for the commented line below.
$$added: function(snap, prevChild) {
var i = this.$indexFor(snap.name());
if( i === -1 ) {
var rec = snap.val();
if( !angular.isObject(rec) ) {
rec = { $value: rec };
}
rec.$id = snap.name();
rec.$priority = snap.getPriority();
$firebaseUtils.applyDefaults(rec, this.$$defaults);
//This is the line that I added to what I copied from the source
angular.extend(rec, printMessageObj);
this._process('child_added', rec, prevChild);
}
}
For the benefit of others, after reviewing the link that Kato posted, I was able to solve the issue by adding the following, almost all copied directly from the source except for the commented line below.
$$added: function(snap, prevChild) {
var i = this.$indexFor(snap.name());
if( i === -1 ) {
var rec = snap.val();
if( !angular.isObject(rec) ) {
rec = { $value: rec };
}
rec.$id = snap.name();
rec.$priority = snap.getPriority();
$firebaseUtils.applyDefaults(rec, this.$$defaults);
//This is the line that I added to what I copied from the source
angular.extend(rec, printMessageObj);
this._process('child_added', rec, prevChild);
}
}

navigate route with querystring

Will Backbone.Router.navigate set test to true:
var test = false;
var Router = Backbone.Router.extend({
routes: {
'posts': 'showPosts'
},
showPosts: function () {
test = true;
}
});
router = new Router();
Backbone.history.start();
router.navigate('posts?foo=3', {trigger: true});
assert.ok(test);
Eg, will posts?foo=3 fragment will match the posts route by default, or do I have to set another route for that, for example: posts?*querystring?
Thank you
PS: I know there exist the backbone-query-parameters but I want to know just for backbone.
You need to add another route with that expecting parameter :
routes: {
'posts?foo=:foo' : 'showPosts',
'posts': 'showPosts'
},
showPosts: function (foo) {
if(typeof foo != 'undefined'){
// foo parameters was passed
}
test = true;
}
update
You could define the general route to return all the query string and then parse it in the handler :
routes: {
'posts': 'showPosts',
'posts?*queryString' : 'showPosts'
},
showPosts: function (queryString) {
var params = parseQueryString(queryString);
if(params.foo){
// foo parameters was passed
}
}
...
// and the function that parses the query string can be something like :
function parseQueryString(queryString){
var params = {};
if(queryString){
_.each(
_.map(decodeURI(queryString).split(/&/g),function(el,i){
var aux = el.split('='), o = {};
if(aux.length >= 1){
var val = undefined;
if(aux.length == 2)
val = aux[1];
o[aux[0]] = val;
}
return o;
}),
function(o){
_.extend(params,o);
}
);
}
return params;
}
update 2
Here's a live demo to see the code in action.
Just to complement the previous answers, instead of defining two routes that have the same callback, like:
routes: {
'posts': 'showPosts',
'posts?*querystring': 'showPosts'
}
You could have only one route to keep the code cleaner:
routes: {
'posts(?*querystring)': 'showPosts'
}
Backbone docs:
Routes can contain parameter parts, :param, which match a single URL component between slashes; and splat parts *splat, which can match any number of URL components.
If you still want to keep the functionality without the matching you can define two routes
routes: {
'posts': 'showPosts',
'posts?*querystring': 'showPosts'
}
showPosts: function(querystring) {
if (querystring) {
// here you can parse your querystring, for your case the querystring variable is
// 'foo=3'
}
//here you'll show posts according to the querystring (or lack thereof)
}
Here's another take, still using lodash (underscore). Removed the _.map, added a bit of verbosity to the variables, and stripped out the starting '?' if present:
function parseQueryString(queryString)
{
if (!_.isString(queryString))
return
queryString = queryString.substring( queryString.indexOf('?') + 1 )
var params = {}
var queryParts = decodeURI(queryString).split(/&/g)
_.each(queryParts, function(val)
{
var parts = val.split('=')
if (parts.length >= 1)
{
var val = undefined
if (parts.length == 2)
val = parts[1]
params[parts[0]] = val
}
})
return params
}
RFC 3986 "syntax for URIs" states that query parameters shold come before hash fragment.
In URIs a hashmark # introduces the optional fragment near the end of the URL. The generic RFC 3986 syntax for URIs also allows an optional query part introduced by a question mark ?. In URIs with a query and a fragment, the fragment follows the query.
I have this issue handling a redirect I am getting from the server i.e. "http://foo.com/main.html?error=errormessage#site". I would like to route on the query but can't see a way to write the backbone route expression to handle this url. For now I just route on the hash and check for a query by parsing location.search.

Resources