Javascript - VueJS - Array as Parameter to store information - javascript

I have created a method in VueJS that fetches data from an API and can accept different parameters that will make different API requests that retrieve different information.
this is the base method and its parameters:
getContents(url, requestType, collection, param = null)
However inside this method, there is a call to another method that will do the actual API fetch.
The thing is that no matter what the API Call is, the fetched contents will always be saved to the same hardcoded variable (in this case the variable this.contents ):
async goGetIt(url) {
try {
let res = await fetch(url);
this.contents = await res.json(); //in this line you should put your destination array where data will be stored.
} catch (error) {
console.log("The request returned the following error: " + error);
}
}
What I would like to implement is for me to be able to pass a pre-created array that would be passed as argument in this function: getContents(url, requestType, collection, param = null, **destinationArray**) and that would then be used as destination for the fetched data.. This would allow me to have several different API Calls Happening at the same time in the same View or Component and saving information to different arrays. Because if I do not implement it, everytime I have 2 different calls of the same method, all the info from the previous fetch will be replaced with the late method call's info.
Is this possible to do with javascript and VueJS?
thank you for your help.

Related

How to use GraphQL response as a variable in Javascript

I am new to GraphQL and I am have the query working as expected but I am having trouble working with the response.
Query
query {
all_assets(where: {title: "suppliestile-blt9607aa6a28539d2e.zip"}) {
items {
url
}
}
}
Calling Response
var jsondata = JSON.stringify(response.data);
console.log(jsondata);
This is giving me the following response
{"data":{"all_assets":{"items":[{"url":"https://assets.contentstack.io/v3/assets/blt15ad871ba49b8a41/blta52af33b959c061f/6352b5fb3bd922566d8d3f2d/suppliestile-blt9607aa6a28539d2e.zip"}]}}}
Essentially I would like to use the url value as a variable moving forward but I am having trouble extracting it from all of the nested objects and arrays does anyone have any advice to get me pointed in the right direction?
The answer won't differ because it's a Graphql request. It's just a response that you get through the request via response.data.
If you need to access specific object/property within the response , you need to use the index of the object, you can do
const url = response.data.all_assets.items[0].url;

How do I set nested object entries coming from an api?

I got an object where I keep track of several things that the user can fill out, delete, update, etc.
Now, when 'loading' such a project, I make an api call to my backend using axios to retrieve the specific data to send it back to the client. The api call looks like this:
axios.get(`/api/data/${this.$route.params.dataId}`)
.then((response) => {
//Why does this not work?
this.nestedObject = response.data.object
//This DOES work... Why?
this.nestedObject.recipes = response.data.object.recipes
this.nestedObject.cheffs= response.data.object.cheffs
})
.catch((err) => {
console.log("error retrieving data: ", err);
});
Whenever I just set this.nestedObject equal to the data that is coming from the server, it does not work. nestedObject is not updated with the new values. But when I set the individual entries in the object equal to the data that is coming from the server, it does work and nestedObject is updated appropriately. Why is that?

Referencing data I expect to receive from server

new here so apologies if I don't lay this out as you'd expect.
So I'm submitting my reactive form data to the server (mongodb database). I then want to route to a new path passing the ID element that the database returns to the front end as a param in the URL.
This is what I have in the submit function so far:
onsubmit(){
let opdata = null;
this.location.saveOpnote(this.form.value)
.subscribe(response => {
opdata = response
console.log(response)
})
this.route.navigate(['/opnotes/mopsdisplay', opdata._id])
}
So data saves perfectly and backend returns the _id of the new entry. Browser complains:
ERROR TypeError: Cannot read property '_id' of null
My understanding is the browser is looking at this before the asynchronous part of saving to the server is completed and the _id is available.
How do I get round this?
Many thanks.
You want your request to be completed, therefore navigation part should be the last line inside the subscription not outside of it. As your call on save is asynchronous as you mentioned, navigation block gets executed before the save operation finishes.
You can create a new function navigateToMopsDisplay just to navigate to your desired route. Once the Opnotes is saved, the opdata response can be sent to navigateToMopsDisplay with opdata._id and can be navigated
navigateToMopsDisplay(id) {
this.route.navigate(["/opnotes/mopsdisplay", id]);
}
onsubmit() {
this.location.saveOpnote(this.form.value).subscribe(response => {
const opdata = response;
this.navigateToMopsDisplay(opdata._id);
});
}

fetching the data dynamically from RestEnd points

I need to get the data from the REST endpoint and display it in some sort of filterable table, and update it if anything changes in the server.
(I dont want to get the data from static JSON file but everytime i make a GET call to rest end point i will get the data which is in json format)
are there any tutorials which can help me with this?
To make a fetch call to an API endpoint, you would use JavaScripts built in fetch method. See below, I've built a fetch and even put in a dummy endpoint that returns actual JSON so you can see that it's working. Just replace the URL right after fetch with the the API endpoint you want to get JSON from...
fetch('https://jsonplaceholder.typicode.com/users')
.then((response) => {
return response.json()
})
.then((data) => {
console.log(data)
})
.catch((err) => {
console.log(err)
})
The first .then makes sure the data is turned back into JSON and then passes the data down to the second .then. Inside that second .then is where you would handle the response by using (in this case) 'data' as the variable name. You can set those parameters to whatever you want to call them though. Finally, the .catch simply console logs the error message if the fetch is unsuccessful.
Here is a repl so you can see it working. Just hit run and you'll see the response: https://repl.it/repls/UnfoldedVibrantProcessor
You'll need to continuously call the API endpoint to check for the data, updating the local dataset with each response. If the API is self-developed,restful and used solely for this example, then the data will be cached so it won't have a massive impact on performance/resources (if the data isn't changing rapidly).
Just shove the code you're using to call the endpoint e.g. Ajax calls within a setInterval() loop and it should work fine, updating the UI (table & contents) as you're re-performing the process over and over.
setInterval(function(){
some AJAX call getting data ...
... use the AJAX response (data) to re-draw/update the table contents
}, 3000);
The process for getting what you want:
Implement continuous API caller (setInterval); initiated on document load.
Learn and Implement external API request e.g. AJAX
Parse data, create HTML using data to create a table structure or use external table library.
Use created HTML to dynamically modify the DOM using document.getElementById("#table you made in your html").innerHTML = ^#3

node.js and hapi: fetching data from a database synchronously

Coming from a .net world where synchronicity is a given I can query my data from a back end source such as a database, lucene, or even another API, I'm having a trouble finding a good sample of this for node.js where async is the norm.
The issue I'm having is that a client is making an API call to my hapi server, and from there I need to take in the parameters and form an Elasticsearch query to call, using the request library, and then wait for the instance to return before populating my view and sending it back to the client, problem being is that the request library uses a callback once the data is returned, and the empty view has long been returned to the client by then.
Attempting to place the return within the call back doesn't work since the EOF for the javascript was already hit and null returned in it's place, what is the best way to retrieve data within a service call?
EX:
var request = require('request');
var options = {
url: 'localhost:9200',
path: {params},
body: {
{params}
}
}
request.get(options, function(error, response){
// do data manipulation and set view data
}
// generate the view and return the view to be sent back to client
Wrap request call in your hapi handler by nesting callbacks so that the async tasks execute in the correct logic order. Pseudo hapi handler code is as following
function (request, reply) {
Elasticsearch.query((err, results) => {
if (err) {
return reply('Error occurred getting info from Elasticsearch')
}
//data is available for view
});
}
As I said earlier in your last question, use hapi's pre handlers to help you do async tasks before replying to your client. See docs here for more info. Also use wreck instead of request it is more robust and simpler to use

Categories