I am subscribing to my data from an http get method:
getEds(): void {
this.edService.getEds()
.subscribe((eds: Education) => {
this.eds = eds.educationData;
console.log(this.eds:codeschool);
});
}
I am trying to display my courses for codeschool in an *ngFor loop but do not know how to access the data. My console log will show the entire array of objects so I know I am receiving the correct info. I've tried various syntax:
.subscribe((eds: any) => {
this.eds = eds.educationData.course;
.subscribe((eds: any) => {
this.eds = eds.educationData['codeschool'];
.subscribe((eds: any) => {
this.eds = eds.educationData.codeschool;
None of these syntax work and the log shows undefined. I found this page which has great info and what I tried to use as a baseline.
Access / process (nested) objects, arrays or JSON
However, I do not know what is wrong or why I cannot get the data I need. When I use
.subscribe((eds: any) => {
this.eds = eds.educationData;
and I log out (this.eds), my log shows:
[{…}]
0:{codeschool: Array(14), egghead: Array(6)}
length:1
__proto__:Array(0)
Beyond this I haven't been able to get the data I want...... :(
use this :
eds.educationData[0].codeschool
Related
I am building a nativescript mobile application which consume graphql API, and I am using apollo client via apollo boost.
The problem appear when I am trying to send array of objects inside the mutation like below:
let {
to,
total,
drugList
} = order
apolloClient.mutate({
mutation: gql `mutation {
makeOrder(
to: "${to}",
total: ${total},
drugList: ${drugList}
){
id
}
}`
}).then((res) => {
console.log(res)
}).catch((error) => {
console.log(error)
})
I have tried to log the drugList inside a template literals like:
console.log(`${drugList}`)
But I got [object object],[object object] then I have tried to use ${[...drugList]} instead and I got the desired structure of array of objects but the mutate function of apollo client doesn't accept it (doesn't execute the mutation or log an error).
Am I miss something to make it run or are there any recommendation to run it?
Thanks to Bergi, after his notice that gql-tagged template literal cannot be compared to the simple template string in a console.log test.
So I have searched around this and figured out that variables property would solve this problem.
Here is the final result:
let {
to,
total,
drugList
} = order
apolloClient.mutate({
mutation: gql `mutation ($to: ID!, $total: Float!, $drugList: [OrderDrugsListInput!]!) {
makeOrder(
to: $to,
total: $total,
drugList: $drugList
){
id
}
}`,
variables: {
to: to,
total: total,
drugList: drugList
}
}).then((res) => {
console.log(res)
}).catch((error) => {
console.log(error)
})
This question already has an answer here:
How to get data from firestore DB in outside of onSnapshot
(1 answer)
Closed 3 years ago.
I read a collection about book checkout from firestore in create().
The data is store in checkout array that declared in data().
export default {
name: "checkout-history",
data() {
return {
checkout: []
]
};
},
created() {
db.collection("checkout")
.get()
.then(querySnapshot => {
querySnapshot.forEach(doc => {
const data = {
id: doc.id, // firebase document id
book_did: doc.data().book_did,
borrowed_date: doc.data().borrowed_date,
copies_did: doc.data().copies_did,
due_date: doc.data().due_date
};
this.checkout.push(data); // push to array
});
});
console.log(this.checkout) // show data, as in the image below
console.log(this.checkout.length) // get 0
console.log(Object.keys(this.checkout).length) // get 0
}
......
When I run console.log(this.checkout);, console show this:
However, I cannot iterate it, the console show this.checkout.length is 0
I also tried to use Object.keys but no luck.
Object.keys(this.checkout).forEach(key => {
const keys = this.checkout[key];
console.log(keys);
});
I really don't know what to do anymore.
I read many answers online and tried most of them, but none of them work.
I guess you are executing your code before the completion of the request.
If you hover over the little blue i icon, it says:
Value below was evaluated just now.
Data is loaded from Firestore (and from most modern web APIs) asynchronously. This means that the rest of your code continues to execute after you start the query, and then when the data comes back from the database, your then() callback is called. This in turn means that all code that needs access to the data from the database, must be inside the then() callback.
db.collection("checkout")
.get()
.then(querySnapshot => {
querySnapshot.forEach(doc => {
const data = {
id: doc.id, // firebase document id
book_did: doc.data().book_did,
borrowed_date: doc.data().borrowed_date,
copies_did: doc.data().copies_did,
due_date: doc.data().due_date
};
this.checkout.push(data); // push to array
console.log(this.checkout) // show data, as in the image below
console.log(this.checkout.length) // get 0
console.log(Object.keys(this.checkout).length) // get 0
});
});
}
......
Also see:
How to get data from firestore DB in outside of onSnapshot
Why are Firebase APIs asynchronous?
This is the method I'm using, pretty simple.
DailyCountTest: function (){
this.$store.dispatch("DailyCountAction")
let NewPatientTest = this.$store.getters.NewPatientCountGET
console.log(NewPatientTest)
}
The getter gets that data from a simple action that calls a django backend API.
I'm attempting to do some charting with the data so I need to assign them to variables. The only problem is I can't access the variables.
This is what the console looks like
And this is what it looks like expanded.
You can see the contents, but I also see empty brackets. Would anyone know how I could access those values? I've tried a bunch of map.(Object) examples and couldn't get any success with them.
Would anyone have any recommendation on how I can manipulate this array to get the contents?
Thanks!
Here is the Vuex path for the API data
Action:
DailyCountAction ({ commit }) {
axios({
method: "get",
url: "http://127.0.0.1:8000/MonthlyCountByDay/",
auth: {
username: "test",
password: "test"
}
}).then(response => {
commit('DailyCountMutation', response.data)
})
},
Mutation:
DailyCountMutation(state, DailyCount) {
const NewPatientMap = new Map(Object.entries(DailyCount));
NewPatientMap.forEach((value, key) => {
var NewPatientCycle = value['Current_Cycle_Date']
state.DailyCount.push(NewPatientCycle)
});
}
Getter:
NewPatientCountGET : state => {
return state.DailyCount
}
State:
DailyCount: []
This particular description of your problem caught my eye:
The getter gets that data from a simple action that calls a django backend API
That, to me, implies an asynchronous action and you might be getting a race condition. Would you be able to post a sample of your getter function to confirm my suspicion?
If that getter does indeed rely on an action to populate its contents, perhaps something to the effect of the following might do?
DailyCountTest: async () => {
await this.$store.dispatch('DailyCountAction')
await this.$store.dispatch('ActionThatPopulatesNewPatientCount')
let NewPatientTest = this.$store.getters.NewPatientCountGET
// ... do whatever with resulting array
}
You can also try with a computer property. You can import mapGetters
import { mapGetters } from 'vuex'
and later in computed properties:
computed: {
...mapGetters(['NewPatientCountGET'])
}
then you can use your NewPatientCountGET and it will update whenever the value changes in the store. (for example when the api returns a new value)
Hope that makes sense
I'm just starting out with React and ES6 so apologies if this is a bit of a simple one.
I'm currently playing round with the FoursquareAPI. I'm using ES6 fetch to return a series of objects (they're actually different venues in different parts of the world) which are then mapped and returned and stored in the application's state. This works fine and returns what I want:
// method to call api
getVenues: (searchTerm) => {
const fetchVenuesURL = `${urlExplore}${searchTerm}&limit=10&client_id=${clientId}&client_secret=${clientSecret}&v=20180602`;
return fetch(fetchVenuesURL).then( response => {
return response.json();
}).then( jsonResponse => {
if (jsonResponse.response.groups[0].items) {
return jsonResponse.response.groups[0].items.map(item => (
// populate venues
{
id: item.venue.id,
name: item.venue.name,
address : item.venue.location.address,
city : item.venue.location.city,
country : item.venue.location.country,
icon : item.venue.categories[0].icon
}
));
} else {
return [];
}
});
// method in App.js to setState
search(term){
Foursquare.getVenues(term).then(foursquareResponse => {
this.setState({venues: foursquareResponse});
});
}
The problem arises when I need to fetch photographs associated with each of the 'venues' returned by the original fetch. These come from a different endpoint. I'm not sure what the best approach is.
One way would be to have two separate api calling methods and then somehow populate an empty photos field of the first with the photos from the second back in App.js but that seems clunky.
My instinct is to somehow nest the Api calls but I'm uncertain about how to go about this. I'm hoping to do something along the lines of somehow applying a method to each iteration of the first mapped object, something along the lines of but not sure how to link them together so that the second goes into the photo property of the first:
{
id: item.venue.id,
name: item.venue.name,
address : item.venue.location.address,
city : item.venue.location.city,
country : item.venue.location.country,
icon : item.venue.categories[0].icon
photos : []
}
const fetchPhotosURL = `${urlPhotos}${venueId}/photos?limit=10&client_id=${clientId}&client_secret=${clientSecret}&v=20180602`;
return fetch(fetchPhotosURL).then( response => {
return response.json();
}).then( jsonResponse => {
if (jsonResponse.response.photos.items) {
console.log(jsonResponse.response.photos.items[0].venue)
return jsonResponse.response.photos.items.map(item => (
{
id : item.id,
created: item.createdAt,
prefix: item.prefix,
suffix: item.suffix,
width: item.width,
height: item.height,
venue: item.venue
}
));
} else {
return [];
}
})
Can anyone point me in the right direction with this. I'm guessing that it's one of those things that isn't that hard once you've done it once but I'm finding it difficult.
Thanks in advance.
I need to update objects in my database, so I do this:
const items = af.database.list('/items');
items.update('key-of-some-data1', { size: newSize1 });
items.update('key-of-some-data2', { size: newSize2 });
This works like a charm, but I would like to update items with a "data fan-out" as described here:
https://firebase.google.com/docs/database/web/read-and-write
https://firebase.googleblog.com/2015/10/client-side-fan-out-for-data-consistency_73.html
So I do:
var updates = {};
updates['key-od-some-data1']= { size: newSize1 };
updates['key-od-some-data2']= { size: newSize2 };
items.update(updates);
Unfortunately I get this error:
zone.js:140 Uncaught Error: Error in ./AppComponent class AppComponent - inline template:30:2 caused by: Method requires a key, snapshot, reference, or unwrapped snapshot. Got: object
Is it even possible to update with data fan-out to the database with angularfire2? Does data fan-out work only with the same object key or something?
Replace:
const items = af.database.list('/items');
with:
const items = af.database.object('/items');