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

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?

Related

Javascript - VueJS - Array as Parameter to store information

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.

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

Problem with React making Get request to Node(express)

As the title says, i have a part of my react app that tries to get some data from my database, making a select based on the value I passed to it. So im gonna go ahead and first show the code where i think the problem lies:
So first, this is the function from one of my forms that sends the request to the server, i know code is probably ugly, but i can tell from the console.logs that the parameters im sending are what i intend to send(a string called "licenciaInput"
async handleClickLicencia (event) {
event.preventDefault();
console.log(this.state);
console.log("licenciaInput: "+this.state.licenciaInput);
const datoBuscar = this.state.licenciaInput;
axios.get('http://localhost:3001/atletas/:licencia',this.state)
.then(response =>{
console.log(response)
})
.catch(error =>{
console.log(error)
})
And then, i have this function which is called in that localhost route which attempts to get "licencia", and launch a select in my postgresql db where licencia="whatever", you can see the sentence in the code:
const getAtletasByLicencia = (request, response) => {
const licencia = request.body.licenciaInput;
console.log("Request: "+request);
console.log("what the server gets: "+licencia);
// const licencia = request.licenciaInput;
const sentencia ="SELECT * FROM atleta WHERE licencia ='"+licencia+"'";
pool.query(sentencia, (error, results) =>{
if(error){
throw error
}
response.status(200).json(results.rows)
})
}
As you can see, i have console.logs everywhere, and i still cannot access whatever element i send, because i always get on the server console "undefined" value.
TLDR:How can i access the "licenciaInput" i passed from my client form to my server, i have tried request.body.licenciaInput, request.params.licenciaInput, and request.licenciaInput, but none of those seem to work
I also know i have to treat after that the data i receive from the server, but i need to solve this before looking two steps ahead. Im also really new to React and node/express, so feel free to burn me with good practices im not meeting.Thanks in advance
EDIT: Im also adding this code that i have which shows the route for my method in the server:
app.get('/atletas/:licencia', db.getAtletasByLicencia)
As #Gillespie59 suggested that i should send a POST request, but i dont think i should if im both trying to send a parameter to the server to make a select, and then send the results back to the client
Change your request to:
axios.get(`http://localhost:3001/atletas/${this.state.licenciaInput}`)
...
and your route (if you are using express) should look like this:
app.get('/atletas/:licencia', function (req, res) {
var licencia = req.params.licencia
...
})
As you are using request.body you should send a POST request with axios and add a body.

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

Cannot update Parse object via REST API

Right, so I'm simply trying to update my object via the REST API. My request succeeds, I get a 200 response back containing the latest updated timestamp, but the object's column value has not changed.
My Movies class has a title and a genre column, the rights on the class are set to public read write on all rows.
Here is some code
var data = {title:'The Revenant'};
qwest.put('https://api.parse.com/1/classes/Movies/myObjectId', JSON.stringify(data))
.then(function(xhr, response) {
console.log(response);
})
.catch(function(xhr, response, e) {
console.log(e);
});
The response I get back?
{"updatedAt":"2016-01-24T07:59:54.977Z"}
So the request succeeded but if I GET the object again or check in the Parse admin page, the object has not changed. What gives?
EDIT
FYI, if I use the Javascript SDK, I can update the model.
var Movies = Parse.Object.extend("Movies");
var query = new Parse.Query(Movies);
query.get(myObjectId, {
success: function (movie) {
movie.set("title", data.title);
movie.save();
},
error: function (object, error) {
console.log(error);
}
});
This updates the model. For my particular use case though, I would really prefer to use the REST API rather than the SDK, but I guess this means it is not a permissions issue or an id mismatch etc.,
code snippet
qwest.put('https://api.parse.com/1/classes/Movies/Dh7zjiP9KW', data, {dataType:"json",headers:{'x-parse-application-id':'XXX','X-Parse-REST- API-Key':'XXX'}})
.then(function(xhr, response) {
console.log(response);
})
.catch(function(xhr, response, e) {
console.log(e);
});
The response you're getting indicates that the object was updated successfully. Double check that you're looking at the correct object, and that the "updatedAt" field matches the response you saw earlier.
What happens if you fetch the object right away, using the same "qwest" client and https://api.parse.com/1/classes/Movies/myObjectId resource URL (with the correct object id)?
Try removing JSON.stringify(data) and just pass data,

Categories