multiple url get async await axios VUE.JS - javascript

Probably this is a very stupid question, i'm new in vue.js and javascript, so please forgive me if the question is not properly explained or the answer is simple... I have a problem I wanted to get from two different api and then display it for.
async mounted() {
const { data } = await this.axios.get(
"http://some-ip/api/get"
).then(response => {
this.items = response.data.data.items
})
;
const { data2 } = await this.axios.get(
"http://some-ip/api2/get"
).then(response => {
this.items2 = response.data.data.items
})
;
First api works perfectly, the second no works...
Any good soul who can help this newbie? (if can explain the why of the solution as well, for understand, will be amazing!!)
Thanks in advance!!

It seems like you're trying to destructure data2 from Axios response which doesn't exist on that object, only data does. You have to use data to get the actual response data.
Axios response schema for reference: https://axios-http.com/docs/res_schema
Consider this example as it destructures the data props but sets the name to data2:
const { data: data2 } = await this.axios.get(
"http://some-ip/api2/get"
).then(response => {
this.items2 = response.data.data.items
})
;

Related

NextJS (v13) How do I dynamic request data inside of a server component

Been experimenting with some server components and nextjs (v13) and have encountered something that i'm not sure how to do. Let's say in theory I wanted to have something with this functionality (with the requests running serverside)
const ClientComponent = () => {
// this value cannot be hardcoded into the server component, nor can we change
// this value at any point in time during the clients components life (just using const for example)
// in reality it'd be set in some other format
const id = "some-id"
return <ServerComponent id={somethingId} />
}
const fetchData = async (id: string) => {
// writing this off top of head, not sure if correct syntax but some basic post request using the id
const res = await fetch("someUrl", { data: id });
const data = await res.json();
return { data };
}
const ServerComponent = async ({ id }: { id: string }) => {
if (!id) return null;
const { data } = await fetchData(id);
return (
<div>
{data.someValue}
</div>
);
}
How would I go about doing something of this nature? is this considered "improper" / "bad practice"? if so what would be a better way to go about doing this? Keep in mind that ClientComponent could be three-four nodes down (with each node being a client component)
Thanks :)

Get data from google firebase's firestore, put into global object/array javascript, react

I am trying to read from firestore and push that data into a global variable. I am able to push however the array acts differently outside the function (I've attached a screenshot from the console showing the dif). For example I can call data[0] or data[1] inside the function just fine but outside it returns "undefined". Can anyone help with this?
This is for a react project, so if there is a way to do it using react hooks or something like that, I can implement no problem.
let fbData = [];
const GetData = async () => {
const q = query(collection(db, "surveys"), where("surveyComplete", "==", true));
const querySnapshot = await getDocs(q);
querySnapshot.forEach((doc) => {
fbData.push({
[doc.data().surveyId]: {
"name": doc.data().surveyName,
"id": doc.data().surveyId
}
});
},
function (error) {
console.log("Error getting documents: ", error);
});
}
And yes I know the way I structure my data is weird, I'm planning on fixing it once I figure this issue out.

Use GET to return records based on nested fields

I am trying to retrieve records based on a value in a mongo dataset that is in a nested object.
data is an object and documentId is a field within it and I want to retrieve just the objects within data that have the documentId of "5da713edf0a1645ae95b11oo"
I tried this code
const res = await axios.get('/api/card',{
params:{
data:documentId: "5da713edf0a1645ae95b11oo"
}
});
but it just returns all the records
Try one of these:
const res = await axios.get('/api/card',{
params:{
documentId: "5da713edf0a1645ae95b11oo"
}
});
This would be a GET request to /api/card?documentId=5da713edf0a1645ae95b11oo
or
const res = await axios.get('/api/card',{
params:{
data: {
documentId: "5da713edf0a1645ae95b11oo"
}
}
});
This would be a GET request to something like /api/card?data=%7B%22documentId%22%3A%225da713edf0a1645ae95b11oo%22%7D
...where %7B%22documentId%22%3A%225da713edf0a1645ae95b11oo%22%7D is URL encoded version of {"documentId":"5da713edf0a1645ae95b11oo"}
according to the documentations it says that we can not do what you have done.
axios.get('/api/card')
.then((res) => {
const data = res.data.id;
//handle your response here.
//can write your logic to retrieve your specific data
});
for further in formations refer this doc
I'm going to assume the data you're receiving on the response is an array of objects. You can filter through it. You're going to have to loop through the data though.
const res = await axios.get('/api/card')
const filteredData = res.data.filter((item) => item.documentId === '5da713edf0a1645ae95b11oo')
You can try this:
data_get() {
axios.get('/api/card')
.then((res) => {
this.setState({
documentId: res.data.id, //5da713edf0a1645ae95b11oo
});
});
}

json and data returned from api's

I'm new to coding and just paying around, but i have what I think is really simple problem, but just don't have the necessary vocabulary to express it properly. Here is my code, its for currency conversion.
app.get('/currency', (request, response) => {
const from_currency = request.query.from;
const to_currency = request.query.to;
const amount = request.query.amount;
const exchange = `${from_currency}_${to_currency}`
//https://free.currencyconverterapi.com/api/v5/convert?q=USD_PHP&compact=y
const currencyUrl = `https://free.currencyconverterapi.com/api/v5/convert?q=${from_currency}_${to_currency}&compact=y`;
const requestOptions = {
uri: currencyUrl,
json: true
};
requestPromise(requestOptions)
.then((data) => {
//const responseData = getCurrentCurrencyJSON(data);
response.json(data); //responseData
})
.catch((error) => {
console.log(error.message);
response.json({
messages: [{
text: 'Sorry there was an error!'
}]
});
});
});
This returns, from the API, {"USD_GBP":{"val":0.73897}}, which is fine and I can return the value if i write response.json(data.USD_GBP.val); however I want to be able to vary the currencies im converting to and from, so how do I make the USD_GBP in the response.json dynamic?
thanks if anyone can help.
If the api is always going to return an object with than single attribute, you can do something like this:
res = {"USD_GBP":{"val":0.73897}};
res[Object.keys(res)[0]].val
Not the nicest, but it works.

Firebase firestore how to get reference data without additional request?

When I have fetched places that we can see in screenshot below, I need get their data, but it's reference to data, I can get the data without additional request like place.ref.data()? If I have 30 places, should I make 30 requests, really? I use react native and the ref object has type DocumentReference https://rnfirebase.io/docs/v3.1.x/firestore/reference/DocumentReference
You need to create your own populate method.
Here's one example I made where my collection eventSchedule has references to events, then I have the array of events and I want to get the events from each eventSchedule... That's how I did:
...
const docRef = db.collection("eventSchedule").doc(dayName);
try {
const doc = await docRef.get();
if (doc && doc.exists) {
const eventSchedule = doc.data();
if (eventSchedule.activeEvents) {
const activeEventsRefs = eventSchedule.activeEvents;
eventSchedule.activeEvents = [];
await activeEventsRefs.reduce(
async (promise: any, event: any) => {
await promise;
const childDoc = await event.get();
if (childDoc) {
eventSchedule.activeEvents.push(childDoc.data());
}
},
Promise.resolve()
);
}
} else {
logMessage += `No docs found for eventSchedule for today - ${dayName}`;
}
} catch (error) {
logMessage += `Error getting document ${JSON.stringify(error)}`;
}
So I used reducer to handle the promises. It works like a charm and it was the simplest "manual" way of doing this.
Also if you use React + Redux + Firebase, you can check the library react-redux-firebase that already implements a lot of stuff including the populate that is, similar to the MongoDB populate and the SQL Join:
http://react-redux-firebase.com/docs/populate.html

Categories