Meteor fetch on client undefined outside of helper - javascript

I am trying to fetch an entry in a collection with:
client/views/home.js:
criticalCrewNumber = ConfigValues.find({
name: 'criticalCrewNumber'
}).fetch()[0].value;
But I'm getting error:
Uncaught TypeError: Cannot read property 'value' of undefined
If I run the code in the browser console, the desired value is returned as a string.
I have tried various things, e.g. using findOne; placing the code elsewhere in the app; using iron-router waitOn for the subscription to come, etc. Every attempt so far has failed as I end up with undefined.
Here's how the collection is defined, published and subscribed to:
lib/config/admin_config.js:
ConfigValues = new Mongo.Collection("configValues");
ConfigValues.attachSchema(new SimpleSchema({
name: {
type: String,
label: "Name",
max: 200
},
value: {
type: String,
label: "Value",
max: 200
}
}));
both/collections/eventsCollection.js:
if (Meteor.isClient) {
Meteor.subscribe('events');
Meteor.subscribe('config');
};
server/lib/collections.js
```
Meteor.publish('events', function () {
return Events.find();
});
Meteor.publish('config', function () {
return ConfigValues.find();
});
```
Does anyone know what's going on? Thanks.

Consider using ReactiveVar (and Meteor.subscribe callbacks):
criticalCrewNumber = new ReactiveVar();
Meteor.subscribe('config', {
onReady: function () {
var config = ConfigValues.findOne({name: 'criticalCrewNumber'});
if (config) {
criticalCrewNumber.set(config.value);
} else {
console.error('No config value.');
}
},
onStop: function (error) {
if (error) {
console.error(error);
}
}
});

Related

Apollo Client is not refreshing data after mutation in NextJS?

Here is the page to create a User
const [createType, { loading, data }] = useMutation(CREATE_USER_CLASS) //mutation query
const createUserClass = async (event) => {
event.preventDefault();
try {
const { data } = await createType({
variables: {
userClassName,
},
refetchQueries: [{ query: STACKINFO }],
options: {
awaitRefetchQueries: true,
},
});
setNotification({
message: 'User class created successfully',
code: 200,
});
handleClose();
} catch (e) {
setNotification({ message: e.message, code: 400 });
handleClose();
}
};
The thing is I can see inside the network tab the API is calling twice, which is not a good way, but I can see the newly added data , but the page is not refreshing. Kindly help me
I was also struggling with a similar problem and I stepped into your question. I don't know which version of Apollo Client you are using, but I think that instead of using refetchQueries() method, you can try to use update() to clear the cache. This way you will notify UI of the change. Something like this:
createType({
variables: {
userClassName,
},
update(cache) {
cache.modify({
fields: {
// Field you want to udpate
},
});
},
})
This is a link for reference from official documentation's page:
https://www.apollographql.com/docs/react/data/mutations/#:~:text=12-,update
I hope it helps!

How can I pass an error message from the server backend to vue frontend

I am working on error handling for an application built in Vue/Vuetify. I am using external pagination for a datatable that links to an API that only allows so many hits in a period of time. Because of that, I'm trying to pass through and display an error of "Too Many Requests" on the front end for users when they hit that limit.
The issue I'm having though is passing that error from the backend server to the frontend. When it errors on the front end, it just gives a 500 error. However, the server log is giving me the actual error happening. How can I get that to pass? Below is the relevant javascript code from the server and the front end.
For note: I've been using eventbus to display errors throughout the project. But up until now, I haven't had to pass any from the back to front.
Backend Server
module.exports = {
async find(ctx) {
var page = ctx.query.page;
var key = '';
var locale = ({ location: '', location_type: '', page: page });
const sdk = require('api')('#');
try {
var response = await sdk.auth(key)['grants_funders'](locale);
}
catch (err) {
console.log(err);
}
;
// .then(res => console.log(res))
// .catch(err => console.error(err));
// console.log(response);
return response
}
};
FRONTEND
export default {
name: "Search",
components: {},
props: ["funderDirectories", "serverItemsLength"],
data() {
return {
page: 1,
usericon: usericon,
greentick: greentick,
listicon: listicon,
training: training,
keyword: null,
funderHeaders: [
{ text: "Organization", value: "funder_name" },
{ text: "City", value: "funder_city" },
{ text: "Country", value: "funder_country" },
{ text: "Count", value: "grant_count" },
],
myloadingvariable: false,
pageCount: 1,
itemsPerPage: 25,
};
},
watch: {
page() {
Vue.$funderService.find({ page: this.page }).then((res) => {
this.funderDirectories = res.data.rows;
this.serverItemsLength = res.data.total_hits;
});
},
},
methods: {},
computed: {
filteredFunderDirectories() {
if (!this.keyword) {
return this.funderDirectories;
}
return this.funderDirectories.filter(
(q) =>
q.funder_name.toLowerCase().indexOf(this.keyword.toLowerCase()) !== -1
);
},
},
};
Ultimately figured it out. added the following to the backend catch
return ctx.send({errorStatus:"Too Many Requests. Please Wait"},429)
And I was able to call

Vuejs form submit not working

I want to submit the values in my form but each time I press the submit button I get the following error:
Uncaught TypeError: login is not a function
at Object.submit [as fn] (eval at Yr (vue.min.js:7), <anonymous>:2:369)
at HTMLFormElement.<anonymous> (vue.min.js:6)
In my HTML code I have my form declared as such: <form v-on:submit.prevent="login">
In the JS it looks like this:
// register
Vue.component("login-form",
{
template: // THE HTML FORM
,
data: function () {
return data;
},
ready: function () {
this.isAuthenticated = this.checkIfAuthenticated();
this.userName = localStorage.getItem("id_name");
},
methods: {
checkIfAuthenticated: function () {
const users = [
{
id: 1,
name: "tom"
},
{
id: 2,
name: "brian"
},
{
id: 3,
name: "sam"
}
];
this.$set("users", users);
},
login: function () {
const headers = { "Content-Type": "application/x-www-form-urlencoded" };
$.ajax({
url: "/token",
type: "post",
data: `username=${this.login.username}&password=${this.login.password}`,
headers: headers,
success: function (data) {
console.info(data);
},
error: function() {
this.isValid = false;
}
});
}
}
});
// create a root instance
var vue = new Vue({
el: "#loginForm"
});
As you see the login function is in my methods, so I don't see why vue is throwing the error
Edit: inluced a JSFiddle. The problem happens when you submit the form (after you click on login)
Looks like your instance has a conflict. There is a login property in a component and there is a login method in Vue instance. Try to use different names. Issue at vuejs github:
Both data properties and methods will be set on the instance, so the
short answered is: don't use conflicting names :)

Backbone targetModel = undefined

I am running into this issue with backbone where the model seems to be undefined to backbone, though all scripts are loaded.
(I am using require to load backbone and other javascript files).
So whenever I do a collection.fetch I get this error in firebug:
TypeError: targetModel is undefined
When I run the script it holds at this point:
if (attrs instanceof Model) {
id = model = attrs;
} else {
id = attrs[targetModel.prototype.idAttribute];
}
when I hover with my mouse over targetModel it says: undefined
It somehow doesn't seem to work now and the only thing I did was changing my html template, which only get loaded after the collection.fetch.
Can you please help me out here?
Here is my model:
var OF = OF || {};
OF.UsersMdl = Backbone.Model.extend({
default: {
username: '',
mailinglist: '',
email: ''
},
initialize: function() {
//
},
result: {
success: false,
message: ''
},
validate: function(att) {
}
});
Here is the collection:
var OF = OF || {};
OF.UsersCollection = Backbone.Collection.extend({
initialize: function() {
//
},
parse: function(data){
return data["all-users"];
},
model: OF.UsersMdl,
url: 'php/api/users'
});
And last but not least the router with the require part:
goToUsers: function() {
require(['./models/users', './views/users_view', './collections/user_collection'], function(UsersMdl, UsersView, UsersCollection) {
OF.usersMdl = new OF.UsersMdl;
OF.usersCollection = new OF.UsersCollection;
OF.usersView = new OF.UsersView;
//when the collection is fetched
$.when(OF.usersCollection.fetch({
data: {
"admin": OF.login.attributes.admin,
"session": OF.login.attributes.session
},
success: function(){
//console.log(OF.usersCollection.length);
}
//then render the view
})).then(function(){
OF.usersView.render();
}, 300);
});
},
Here is the JSON which will be retreived by the fetch:
{
"all-users":
[
{
"username":"tester",
"mailinglist":"1",
"email":"tester#tester.test"
},
{
"username":"tester2",
"mailinglist":"1",
"email":"tester2#tester.test"
},
{
"username":"tester3",
"mailinglist":"0",
"email":"tester3#tester.test"
}
]
}
Thanks in advance
I had this same error and banged my head against it for quite a while because backbone is new to me and this was compounding a fetch issue. Anyhow, I eventually figured out that order matters. Doh! (Less obvious when using CoffeeScript and "class" statements I thinks.) With one of my models I was setting the Collection before the Model (thanks to bad example code from the Backbone.js on Rails book). I reversed that and this error went away to reveal my true fetch issue.
Similarly, your model: property may be invalid for this reason or another reason, leaving it undefined when attempting to reference later.
Side note: I had a similar error in Backbone 1.0.0. When I upgraded to Backbone 1.1.0 I then got this exact error at the same point in backbone code.

How to populate jQuery UI Select2 with Restangular

I can't see why Restangular would behave differently inside a jquery-ui callback to the way it does anywhere else. Can you?
The following works in my controller:
Restangular.all('skills').getList().then(function(result) {
console.log(result);
});
However, when I use Restangular inside the query function for a jquery-ui-select2 (via angular-select2), it never makes a request.
HTML:
<input type="text" ui-select2="skillOptions" ng-model="skills">
JavaScript:
$scope.skillOptions = {
multiple: true,
query: function(query) {
// I see this:
console.log("Q:", query.term);
// this silently fails:
Restangular.all('skills').getList({
query: query.term
}).then(function(body) {
// this callback is never reached (nor is the error one)
var skills = body.skills;
console.log("got skills", skills);
query.callback({
data: {
text: 'name',
results: skills
}
});
}, function(error) {
console.error("Error getting skills", error);
});
}
};
Is there another way to use the query callback with Restangular or can anybody see why on Earth this wouldn't work?
The solution was to nest the callback in a $scope.$apply (since I am on AngularJS version 1.1.5) as per this bit of the documentation
Here's some working code:
$scope.skillOptions = {
multiple: true,
query: function(query) {
$scope.$apply(function() {
Restangular.all('skills').getList({
query: query.term
}).then(function(body) {
var skills;
skills = body.skills;
console.log("got skills", skills);
return query.callback({
results: _(skills).map(function(s) {
return {
text: s.name,
id: s.id
};
})
});
}, function(error) {
console.log("Error getting skills", error);
});
});
}
};

Categories

Resources