How to filter Axios get results - search

I have a search bar set up, and what i am trying to do is that when you search for something it will do an axios get call, it will filter through all the results and give you only what you are searching for.
axios.get("api/blogs/" + this.state.pageIndex + "/10").then(res => {
res.filter(function(author) {
return author.firstName === this.state.query;
});
});
I am using react.

#Just code thank you! I managed to figure it out but for whoever else has this same problem the arrow function will fix your problem. Obviously just having a search ajax call would be much better but this is a way around not having one, or if your search ajax call is broken

Related

How to console.log a promisified mongoose query *without* bluebird

I am trying to run a mongoose query and write it to the console without installing yet another library like bluebird. I have been unable to find this in the documentation.
Here is the query:
function activityH(){
return setRecords.find({'item.title': 'marzipan'}
, 'item.title item.quantity').exec();
}
And the context in which I am calling it:
....[a bunch of promises].then(activityF).then(activityG).then(activityH).then(function(doc){console.log(doc);});
All of the prior activities are completing, but nothing is logging even though my query should have results. I feel this is a very basic question but I have looked for hours trying to find a solution and if this is a duplicate, the original answer is very hard to search for!
Do I absolutely need bluebird to do this? E.g. this blog post
Thank you
You could write a little logging function wrapper to help you out. Something like
function log(data) {
console.log(data);
return data;
}
And then add it your Promise chain.
....[a bunch of promises]
.then(log)
.then(activityF)
.then(log)
.then(activityG)
.then(log)
.then(activityH)
.then(log)
If you want some default messaging you could also pass a message string
function log(msg) {
return function(data) {
console.log(msg, data);
return data;
}
}
And then would add to the chain like:
activityA()
.then(log('activityA'))
.then(activityB)
.then(log('activityB'))

Wrapping/intercepting a promise in an inner function

I'm having difficulty finding an answer to my question, perhaps because I don't know how to ask it (what search terms to use). I'm really struggling to understand promises, and have watched a number of tutorial videos and am still not getting some fundamental piece to make it click.
In Node, I am using the request-promise module, which returns a promise when I make a call to an rp() method. I am calling
return rp(service);
from within a function. But what I want to do, instead, is add a .then() handler to this to do some post-processing with the result of the service call, BEFORE returning the promise back to the caller so the caller can still have its own then handler.
How do I accomplish this?
It would be helpful to see your current code to better understand where exactly you are struggling with.
In general, you can think of promises as a placeholder for some future value that you can chain together.
If I understood your question correctly, you would like to make a request to a server, receive the response, do something with the response and return it back to the caller.
const callService = (url) => {
// make sure to return your promise here
return rp(url)
.then((html) => {
// do something with html
return html;
});
};
Now you can call it like so -
callService('http://www.google.com')
.then((html) => {
console.log(html);
}).catch((err) => {
// error handling
});
The common mistake is to omit the return statement in your top level function and subsequent then functions.
Feel free to provide additional details.

Intern and Leadfoot conditional wait until

If there a way to perform .click() after the element become visible.
My function chain is built like that:
this.remote.findByXpath("//div[#data-index='blockContainer']/button[text()='Create new']").then(function(element) {
return element.click().end();
})
Sometimes I got error says 'the element is not visible', is it possible to perform click after the element displayed in browser? I know Leadfoot supplies pollUntil to do similar thing but I don't want to execute xpath at browser side, instead of I want to do until at running server side.
To solve my problem I tried following two ways but doesn't help:
I tried to pass Leadfoot Element to browser side script and check if it is visible. But it seems browser side code doesn't recognize leadfoot/element object.
command.find(...).then(function(element) {
return command.then(pollUntil(
function(element) {
if (element.style.display == 'none') return null;
return true;
}, [element], 60000, 500)).then(function(el){
});
}).click().end();
Also tried to customize pollUntil myself but doesn't work as well
function pollVisible(element, timeout) {
var dfd = new Deferred();
var endTime = Number(new Date()) + timeout;
(function poll() {
element.isDisplayed().then(function (displayed) {
if (displayed) {
dfd.resolve();
}
else if (Number(new Date()) < endTime) {
setTimeout(poll, 500);
}
else {
var error = new Error('timed out; final url is ' + url);
dfd.reject(error);
}
});
})();
return dfd.promise;
}
You've probably had an answer to this by now but here's my solution to this just in case you're still unsure or if anyone else comes across this issue.
I'm not sure why you are polling until an element is visible here. What I would do is set the find timeout of your leadfoot/Session as follows:
this.remote.setFindTimeout(60000)
Then when you invoke the this.remote.findByXPath method, it will automatically search for your element for a maximum of 1 minute (in the case of my above example). If it finds the element within that time, it will then proceed to the next step in your code. If it doesn't find the element within that time, the test case will time out.
You can then simplify your code to (for example):
this.remote
.setFindTimeout(60000)
.findByXpath("//div[#data-index='blockContainer']/button[text()='Create new']")
.click()
.end();
Of course there's no need to set the find timeout every time you wish to find an element in the UI. You can set it once somewhere more appropriate (ie. at the beginning of your test) and it will remain in place for the duration of your test. I'm just doing it here as a means of documenting a full example for you.
Hope this helps!

Node.js: displaying MongoDB results using response.write(), when to execute response.end()

I'm writing a simple app using Node.js. I use no frameworks (to understand how it works at a "lower" level).
What I'm trying to do:
When a GET request is sent to '/list', I use my MongoDB connection to do a find(). Then I want to iterate over each of the returned items, and display them using response.write("" + myItem).
The problem is that I need to execute a response.end() at the end, and I don't know when "the end" will be -- as all my response.write() statements are executed using callbacks.
Here's my code:
db.items.find({state: "free"}, function(err, myItems) {
if (err) {
console.log("There was an error executing the database query.");
response.end();
return;
}
else if (myItems){
myItems.forEach( function(myItem) {
res.write("<p>" + myItem.title + "</p>\n");
});
}
res.write("</div>");
res.end();
}
I have the feeling I'm missing an idiomatic way to use callbacks here... What's the clean way to fix this?
Thank you!
Thats the correct way, your end() will be called at the end of your callback, so after your foreach loop, the function will go on and send the end() method.
Or maybe did I missed the point of your question. But I think not.

Using wait.for with nodejs and mongoskin to avoid callback hell

I m actually developping a little application with mongodb and nodejs to create my REST Api.
I face a problem when I need to access an object reference :
I have a roadmap collection which reference a user object
When I want to get all the roadmaps, I have to loop on my roadmap array to lazy load my users, by the ref ID stored in the roadmap collection
I have a callback problem, the user is not loaded when I need it
I have found a solution using Wait.for library : https://github.com/luciotato/waitfor , but I dont know how it works. I tried everything, but no way to make it work
all: (req,res)->
#em.collection(#collection).find().toArray((err, result)=>
roadmaps = []
for r in result
r.user = #getUser(r.user.oid)
roadmaps.push r
res.send(roadmaps))
getUser: (oid)->
#em.collection('user').findOne {_id: new #objectId(oid)}, (err, res)=>
if !err
return res
return undefined
Does anybody have an idea of how to make it works properly ? Where should I put the wait.lauchFiber ? where should I put the wait.for ?
Thanks for all
I'm not familiar with CoffeeScript, please correct me and I'll edit this answer.
all: (req,res)->
var result = wait.forMethod(#em.collection(#collection).find(), "toArray")
roadmaps = []
for r in result
r.user = #getUser(r.user.oid)
roadmaps.push r
res.send(roadmaps)
getUser: (oid)->
try
return wait.forMethod(#em.collection('user'),"findOne",{_id:new #objectId(oid)})
catch(err)
return undefined
As you can see, for "getUser", if the method is that simple, you better use your version, with the callback.
"where to put the launchFiber()?"
you put the launchFiber when a request arrives. see https://github.com/luciotato/waitfor#proper-use

Resources