Parse cloud code: Can't change result set objects - parse-platform

I have an issue with setting an additional fields to the Parse query result set. An example code is below. Thanks in advance!
When I get the result set from a query in the server-side function I try to run the following code that doesn't work as expected.
querySubscribes.find(
{
success:function(subscribes)
{
for(var i = 0, len = subscribes.length; i < len;i++ ){
subscribes[i]['test'] = 1; // this doesn't work. seems like this object is kind of immutable!
}
response.success(subscribes);
},
error: function(err){
response.error(err);
}
});

Related

i want simple array not [__ob__: Observer]

i call for the api to fetch data, i test it with postman and laravel send it as an array correctly, but vue turn my array into [ob: Observer] and i cant extract my array from it thanks to #Stockafisso it has been solved but
Edit: now my problem is, programming_languages array is only accesible inside getLanguages() method not anywhere else
data(){
return{
answer: '',
maxWrong: '',
programming_languages : []
}
},
methods:{
getLanguages(){
axios.get('/api/toController').then((response)=> {
this.programming_languages = JSON.parse(JSON.stringify(response.data)); //works fine
this.answer = this.programming_languages[Math.floor(Math.random() * this.programming_languages.length)].name; //works fine
this.maxWrong = this.answer.length;// works fine here, i dont want to initiaize answer variable in this method
});
},
randWord(){
this.answer = this.programming_languages[Math.floor(Math.random() * this.programming_languages.length)].name;// it is not working here
//Error in created hook: "TypeError: Cannot read property 'name' of undefined"
this.maxWrong = this.answer.length;// doesn't work here
}
},
created(){
this.getLanguages();
this.randWord();
}
what can i do?
thank you
most probable the error(s) is here:
this.programming_languages.push(JSON.parse(JSON.stringify(response.data)));
you are inserting the Laravel returned array inside the declared programming_languages, while you should override or concat it.
To explain better, a little example:
consider this:
let arr1 = [];
let arr2 = [1,2,3];
if you do arr1.push(arr2) your arr1 will be [[1,2,3]] while you want it to be [1,2,3].
Going back to your problem, to fix it you have two ways:
a)
.then((response)=> {
this.programming_languages = JSON.parse(JSON.stringify(response.data));
b)
.then((response)=> {
let swapArray = [...this.programming_languages];
this.programming_languages = swapArray.concat(JSON.parse(JSON.stringify(response.data)));
If this does not fix the error,
it could be the problem is in the array returned from Laravel. If it has not numeric or not sorted keys, JS will "fill" the missing spaces with Ob. Observer to try to keep the keys.
thank you all, finally i managed to solve it
first i extract array from vue's [ob: Observer]
this.programming_languages = JSON.parse(JSON.stringify(response.data));
special thanks to #stockafisso
and second was that i couldn't get this programming_languages array out of axios method, that happens due to nature of asynchronous call, see this informative link
How do I return the response from an asynchronous call?
i managed to solve it this way, async and await
methods: {
async getPosts(){
await axios.get('/api/hangman').then(response => {
this.programming_languages = JSON.parse(JSON.stringify(response.data));
}).catch(error => console.log(error));
},
randWord(){
this.answer = this.programming_languages[Math.floor(Math.random() * this.programming_languages.length)].name;
this.maxWrong = this.answer.length;
},
},
created(){
this.getPosts().then(() => this.randWord());
}

Rendered more hooks than during the previous render

How to use 2 graphql queries with react-apollo-hooks where the 2nd query depends on a parameter retrieved from the 1st query?
I try to use 2 queries which looks like this:
const [o, setO] = useState()
const { loading: loadingO, error: errorO, data: dataO } = useQuery(Q_GET_O, { onCompleted: d => setO(d.getO[0].id) });
if (loadingO) { return "error" }
const { loading: loadingOP, error: errorOP, data: dataOP } = useQuery(Q_GET_OP, { variables: { o } })
However, when I run my project, react-hooks gives me the following message:
"index.js:1437 Warning: React has detected a change in the order of Hooks called by Upgrade. This will lead to bugs and errors if not fixed. For more information, read the Rules of Hooks"
I would like to know how I can use react-apollo-hooks in order to run a query that depends on another query. It works great if the graphql query variables are known in advance. However, I did not find a solution for variables that come from other query.
The problem here is that you are short circuit returning before all of your hooks have a chance to run.
React will complain if you exit a render function before all of the hooks have a chance to be called.
For example:
function BrokenFoo () {
const query = useSomeQuery();
if (query.loading) return <Loading />
// This will cause some issues because
// it's possible that we return before our useState hook gets called
const [bar, setBar] = useState();
return <SomeComponent bar={bar} setBar={setBar} data={query.data} />
}
To fix:
function FixedFoo () {
// This will be fine because
// all of the hooks have a chance to be called before a return
const query = useSomeQuery();
const [bar, setBar] = useState();
if (query.loading) return <Loading />
return <SomeComponent bar={bar} setBar={setBar} data={query.data} />
}
You can add the skip option to the second query and lose the if condition:
const { loading: loadingOP, error: errorOP, data: dataOP }
= useQuery(Q_GET_OP, { variables: { o }, skip: !o })
from the docs:
If skip is true, the query will be skipped entirely

how to use query result (single row or multiple row) data from node-mysql

I have successfully get data by performing query with node-mysql. But i cant use the query result.
My query result is
{
user_id: 'joy',
user_name: 'joy',
email: 'joy#gmail.com',
socket_id: '/#glVfkRwTqKrlBETiAAAH',
status: 1 }
To use this from i wrote code like :
var value= [];
value = connection.query('SELECT * FROM socket_users WHERE email = ?',[receiver_email], function (error, results,fields) {
// Neat!
if (error) throw error;
console.log(results[0]);
if (results[0].status == 0) {
}else {
console.log("User is online......");
}
//console.log("select one user sql: "+is_Exists.sql);
});
But i got errors at results[0].status line. It says
TypeError: Cannot read property 'status' of undefined
After searching to solve my problem i found a solution. results is an array of an object. So , to use this;
just call
results [array number ]. row attribute name
results[i].status
results[i].user_name
// where i is an integer number

How can I test that an element does not exist on the page with Protractor?

I am trying to test if an element is not present on a page.
I have tried using the following method, but I get an error each time:
Method:
expect(element(CastModule.PersonXpath).isDisplayed()).toEqual(false);
Error: Failed: Timed out waiting for Protractor to synchronize with the page after
seconds. Please see https://github.com/angular/protractor/blob/master/docs/f ...
What method do you recommend?
The error should not be related to the checking for the absence of an element. Try the following:
var elm = element(CastModule.PersonXpath);
expect(browser.isElementPresent(elm)).toBe(false);
See also:
In protractor, browser.isElementPresent vs element.isPresent vs element.isElementPresent
Yeah, testing for NOT visible can be sucky. You should be able to use isPresent(), which means in the dom, where isDisplayed() means it's actually visible, which I'm thinking is your issue. Try...
expect(element(CastModule.PersonXpath).isPresent()).toEqual(false);
You may also want to break this out into a method and use an Expected Condition.
The error doesn't look like it's to do with the element being displayed. It looks like it's to do with page synchronization. Try ignoring the sync, then waiting for angular above the expect with:
browser.ignoreSynchronization = true;
browser.waitForAngular();
expect(element(CastModule.PersonXpath).isDisplayed()).toEqual(false);
To check for visibility (in case isDisplayed or isPresent isn't working), just use:
if (!EC.invisibilityOf(ug.personXpath)) {
throw new Error("Partner logo is not displayed");
}
I managed to find out a solution, using the protractor library.
var EC = protractor.ExpectedConditions; browser.wait(EC.invisibilityOf(element(by.xpath(CastModule.PersonXpath))), 5000).then(function() {
if (EC.invisibilityOf(element(by.xpath(x.LanguagesXpath)))) {
console.log("Persons module is not present - as expected for this scenario");
} else {
throw new Error("Element STILL present");
}
});
});
You can also try below code to handle element displayed or not. Below code returns true or false according to the visibility of the element.
browser.wait(() => {
return element(by.className("claasName")).isDisplayed()
.then(
(hasDisplayed) => {
console.log("Has displayed: "+ hasDisplayed);
return hasDisplayed === false;
}
);
}, 5000)
.then(
() => {
return true;
},
() => {
return false;
}
)
To use presence of element use:
var elm = element(CastModule.PersonXpath);
elm.isPresent().then(function (present) {
if (present) {
element(CastModule.PersonXpath).then(function (labels) {
});
} else {
console.log('Element did not found');
}`enter code here`
expect(elem.isNull===undefined).to.be.equal(true);

parse cloud code query in for loop

I have a table called friends with fields
userid and friendid.
I want to query the database to find a user's friends. This is working fine by using the following code:
Parse.Cloud.define("searchfriend", function(request, response) {
var query = new Parse.Query("friends");
query.equalTo("player", request.params.myid);
query.find({
success: function(results) {
var listfreundids = [];
for (var i = 0; i < results.length; ++i) {
listfreundids[i] = results[i].get("friend");;
}
response.success(listfreundids);
},
error: function() {
response.error("error");
}
});
});
Now I have the problem to find the username matching the friendid because i cannot use a 2nd query within the for loop to query the user database...
Using promises you can split this up into several separate parts. Promises are really awesome to use and really easy to create your own promises too.
What I would do is split this up into a query that finds the friend ids and then a query that finds the friends...
Parse.Cloud.define("searchfriend", function(request, response) {
getFriendIDs(request.params.myid).then(function(friendIDs) {
return getFriendUserNames(friendIDs);
}).then(function(friends) {
response.success(friends);
}), function(error) {
response.error(error);
});
});
// function to get the IDs of friends
function getFriendIDs(myID) {
var promise = new Parse.Promise();
var query = new Parse.Query("friends");
query.equalTo("player", myID);
query.find().then(function(friendIDs) {
promise.resolve(friendIDs);
}, function(error) {
promise.reject(error);
});
return promise;
}
// function to get the friends from a list of IDs
function getFriendUserNames(friendIDs) {
var promise = new Parse.Promise();
var query = new Parse.Query("_User");
query.containedIn("id", friendIDs);
query.find().then(function(friends) {
// here I am just returning the array of friends
// but you can pull the names out if you want.
promise.resolve(friends);
}, function(error) {
promise.reject(error);
});
return promise;
}
You could always user a matches query too...
// function to get friends
function getFriends(myID) {
var promise = new Parse.Promise();
var friendQuery = new Parse.Query("friends");
friendQuery.equalTo("player", myID);
var userQuery = new Parse.Query("User");
userQuery.matchesKeyInQuery("ID", "friendID", friendQuery);
userQuery.find().then(function(friends) {
promise.resolve(friends);
}, function(error) {
promise.reject(error);
});
return promise;
}
This will perform a joined query where it gets the friend IDs first and then uses the friend ID to get the user and returns the user object.
Also, use promises. They are much easier to work with and can be pulled apart into separate working units.
Of course, I have no idea if the syntax here is correct and what the correct names should be or even what your object model looks like but hopefully this can act as a guide.
You do not have to query for each friend id that you have found (inefficient). Instead, after getting the list of friend ids, you can query the user database via sending the list of friend ids with the query.containedIn constraints. This strategy will actually decrease the number of query count.Based on retrieved result you can get friend (previously found) information. One more thing to remember, call response success after the operations are executed.Hope this helps.
Regards.

Resources