Can't get first item in array Angular - arrays

I get some seasons of a series from my API.
After that, I want to use seasons[0] to get the first item in the array.
The problem is that seasons[0] returns undefined.
My Code looks like this :
async ionViewWillEnter() {
const seasons = await this.serieService.fetchCompleteSerie(this.serie);
this.seasons = seasons;
console.log(seasons); //output below
console.log(seasons[0]); //undefined
this.selected = seasons[0]; //undefined
}
my service looks like this:
async fetchCompleteSerie(serie: Serie) {
let allSeasons: any;
let serieSeasons = [];
let allEpisodes: any;
let seasonEpisodes: any;
allSeasons = await this.http.get('https://www.myapp.com/api/seasons/', this.httpOptions).toPromise();
await allSeasons.forEach(async season => {
season["episodes"] = [];
if (season.serie === serie.url) {
allEpisodes = await this.http.get('https://www.myapp.com/api/episodes/', this.httpOptions).toPromise();
allEpisodes.forEach(episode => {
if (episode.season === season.url) {
season.episodes.push(episode);
}
});
serieSeasons.push(season);
}
});
return serieSeasons;
}
The console output looks like this :
Why is it undefined?

The problem is the forEach which DOES NOT RETURN the promises you try to wait for. For that reason seasons[0] is still undefined. But since you log the array to the console and THE SAME array object is used inside your callback, the console refreshes the output after the data arrives. If you clone the array before logging, you will see that its empty console.log([...seasons]);
Simply switch forEach to map and use Promise.all.
async fetchCompleteSerie(serie: Serie) {
let allSeasons: any;
let serieSeasons = [];
let allEpisodes: any;
let seasonEpisodes: any;
allSeasons = await this.http
.get("https://www.myapp.com/api/seasons/", this.httpOptions)
.toPromise();
await Promise.all(allSeasons.map(async season => {
season["episodes"] = [];
if (season.serie === serie.url) {
allEpisodes = await this.http
.get("https://www.myapp.com/api/episodes/", this.httpOptions)
.toPromise();
allEpisodes.forEach(episode => {
if (episode.season === season.url) {
season.episodes.push(episode);
}
});
serieSeasons.push(season);
}
}));
return serieSeasons;
}

Related

How could I write this function so it doesn't setState within the foreach everytime

The function collects role Assignment PrincipalIds on an item in SPO. I then use a foreach to populate state with the Title's of these PrincipalIds. This all works fine but it's inefficient and I'm sure there is a better way to do it than rendering multiple times.
private _permJeChange = async () => {
if(this.state.userNames){
this.setState({
userNames: []
});
}
var theId = this.state.SelPermJEDD;
var theId2 = theId.replace('JE','');
var info = await sp.web.lists.getByTitle('MyList').items.getById(theId2).roleAssignments();
console.log(info, 'info');
var newArr = info.map(a => a.PrincipalId);
console.log(newArr, 'newArr');
// const userIds = [];
// const userNames = [];
// const userNameState = this.state.userNames;
newArr.forEach(async el => {
try {
await sp.web.siteUsers.getById(el).get().then(u => {
this.setState(prevState => ({
userNames: [...prevState.userNames, u.Title]
}));
// userNames.push(u.Title);
// userIds.push(el);
});
} catch (err) {
console.error("This JEForm contains a group");
}
});
}
I've left old code in there to give you an idea of what I've tried. I initially tried using a local variable array const userNames = [] but declaring it locally or even globally would clear the array everytime the array was populated! So that was no good.
PS. The reason there is a try catch is to handle any SPO item that has a permissions group assigned to it. The RoleAssignments() request can't handle groups, only users.
Create an array of Promises and await them all to resolve and then do a single state update.
const requests = info.map(({ PrincipalId }) =>
sp.web.siteUsers.getById(PrincipalId).get().then(u => u.Title)
);
try {
const titles = await Promise.all(requests);
this.setState(prevState => ({
userNames: prevState.userNames.concat(titles),
}));
} catch (err) {
console.error("This JEForm contains a group");
}

React.js Updating state where multiple API endpoints are involved

I'm currently trying to get a project working to test some things and I'm stuck at a point where I'm trying to update the state properly.
I have an endpoint accessed via axios.get("/docker/containers") which will return an array for all IDs of the containers which are currently running on my system this is done like so:
componentDidMount() {
this.interval = setInterval(() => this.updateContainers(), 3000);
};
componentWillUnmount() {
clearInterval(this.interval);
}
At this point my state looks like this:
state = {
containers: [{id: 'id1'}, {id: 'id2'}]
}
The user interface then just shows a list of IDs.
I can then click on an ID on my user interface and it will set a watcher:
state = {
containers: [{id: 'id1', watcher: true}, {id: 'id2'}]
}
The point of the watcher is so that on the next update cycle more detailed information about a particular container is retrieved.
state = {
containers: [{id: 'id1', watcher: true, name: 'container1'}, {id: 'id2'}]
}
Upon clicking the container in the user interface where a watcher is already set then the watcher is dropped and the more detailed information is then no longer retrieved
state = {
containers: [{id: 'id1', watcher: false}, {id: 'id2'}]
}
Where I'm getting stuck is on how to get the more detailed information. My updateContainers method has 3 steps:
Read the response from the API and destruct the state into separate variables, compare the state var with the response var and remove any containers that have gone down (no setState is done here).
Add any new containers from the response to the state that have since come up (again no setState).
...All good thus far...
Loop through the filtered array of containers from steps 1 and 2 and find any containers where a watcher is set. Where it is set perform an API call to retrieve the more detailed info. Finally set the state.
In step 3 I use a forEach on the filtered array and then do an axios.get("/docker/containers/id1") where a watcher has been set otherwise simply keep the container details I already have but that's where I get stuck, Typescript is also giving me the error:
TS2322: Type 'void' is not assignable to type 'IndividualContainer[]'.
currently I have:
updateContainers() {
axios.get('/docker/containers')
.then(response => {
const apiRequestedContainers: string[] = response.data.containers;
// array of only IDs
const stateContainers: IndividualContainer[] = [
...this.state.containers
];
// remove dead containers from state by copying still live containers
let filteredContainers: IndividualContainer[] = [
...this.filterOutContainers(stateContainers, apiRequestedContainers)
];
// add new containers
filteredContainers = this.addContainerToArray(
filteredContainers, apiRequestedContainers
);
return this.updateContainer(filteredContainers);
})
.then(finalArray => {
const newState: CState = {'containers': finalArray};
this.setState(newState);
});
};
updateContainer(containers: IndividualContainer[]) {
const returnArray: IndividualContainer[] = [];
containers.forEach(container => {
if (container.watcher) {
axios.get('/docker/containers/' + container.id)
.then(response => {
// read currently available array of containers into an array
const resp = response.data;
resp['id'] = container.id;
resp['watcher'] = true;
returnArray.push(resp);
});
} else {
returnArray.push(container);
}
return returnArray;
});
};
Any pointers to where my logic fails would be appreciated!
Edit:
Render Method:
render() {
const containers: any = [];
const curStateOfContainers: IndividualContainer[] = [...this.state.containers];
if (curStateOfContainers.length > 0) {
curStateOfContainers.map(container => {
const container_id = container.id.slice(0, 12);
containers.push(
<Container
key = {container_id}
container_id = {container.id}
name = {container.name}
clickHandler = {() => this.setWatcher(container.id)}
/>
);
});
}
return containers;
}
I'm not an expert in TypeScript so I had to change the response to JS and thought you'll re-write it in TS in case it's needed.
async updateContainers() {
const response = await axios.get('/docker/containers')
const apiRequestedContainers = response.data.containers; // array of only IDs
const stateContainers = [...this.state.containers];
// remove dead containers from state by copying still live containers
let filteredContainers = [...this.filterOutContainers(stateContainers, apiRequestedContainers)];
// add new containers
filteredContainers = this.addContainerToArray(filteredContainers, apiRequestedContainers);
const containers = await this.updateContainer(filteredContainers)
this.setState({ containers });
};
async updateContainer(containers) {
return containers.map(async (container) => {
if (container.watcher) {
const response = await axios.get('/docker/containers/' + container.id)
// read currently available array of containers into an array
return {
...response.data,
id: container.id,
watcher: true,
}
} else {
return container;
}
});
}
Here's what I've updated in updateContainer:
I'm now mapping the array instead of doing a forEach
I'm now waiting for the container details API to return a value before checking the second container. --> this was the main issue as your code doesn't wait for the API to finish ( await / async )
The problem is that you are returning nothing from updateContainer method which will return void implicitly:
// This function return void
updateContainer(containers: IndividualContainer[]) {
const returnArray: IndividualContainer[] = [];
containers.forEach(container => {
if (container.watcher) {
axios.get("/docker/containers/" + container.id).then(response => {
// read currently available array of containers into an array
const resp = response.data;
resp["id"] = container.id;
resp["watcher"] = true;
returnArray.push(resp);
});
} else {
returnArray.push(container);
}
// this is inside the forEach callback function not updateContainer function
return returnArray;
});
}
Then you assign void to containers which is supposed to be of type IndividualContainer[] so TypeScript gives you an error then you set that in the state:
updateContainers() {
axios
.get("/docker/containers")
.then(response => {
const apiRequestedContainers: string[] = response.data.containers; // array of only IDs
const stateContainers: IndividualContainer[] = [
...this.state.containers
];
// remove dead containers from state by copying still live containers
let filteredContainers: IndividualContainer[] = [
...this.filterOutContainers(stateContainers, apiRequestedContainers)
];
// add new containers
filteredContainers = this.addContainerToArray(
filteredContainers,
apiRequestedContainers
);
// this return void as well
return this.updateContainer(filteredContainers);
})
// finalArray is void
.then(finalArray => {
// you assign void to containers which should be of type IndividualContainer[]
const newState: CState = { containers: finalArray };
// containers will be set to undefined in you state
this.setState(newState);
});
}
You meant to do this:
// I added a return type here so that TypeScript would yell at me if I return void or wrong type
updateContainer(containers: IndividualContainer[]): IndividualContainer[] {
const returnArray: IndividualContainer[] = [];
containers.forEach(container => {
if (container.watcher) {
axios.get("/docker/containers/" + container.id).then(response => {
// read currently available array of containers into an array
const resp = response.data;
resp["id"] = container.id;
resp["watcher"] = true;
returnArray.push(resp);
});
} else {
returnArray.push(container);
}
// removed the return from here as it's useless
});
// you should return the array here
return returnArray;
}
First, I've commented on errors in your code:
updateContainers() {
axios.get('/docker/containers')
.then(response => {
...
return this.updateContainer(filteredContainers);
// returns `undefined`...
})
.then(finalArray => { ... });
// ...so `finalArray` is `undefined` - the reason for TS error
// Also `undefined` is not a `Promise` so this second `then()`
// doesn't make much sense
};
updateContainer(containers: IndividualContainer[]) {
const returnArray: IndividualContainer[] = [];
containers.forEach(container => {
if (container.watcher) {
axios.get('/docker/containers/' + container.id)
.then(response => {
...
returnArray.push(resp)
// because `axios.get()` is asynchronous
// this happens only some time after
// `.then(finalArray => { ... })` is finished
});
// at this moment code inside `.then()` has not been executed yet
// and `resp` has not yet been added to `returnArray`
} else {
returnArray.push(container)
// but this happens while `forEach()` is running
}
return returnArray;
// here you return from `forEach()` not from `updateContainer()`
// also `forEach()` always returns `undefined`
// so even `return containers.forEach(...)` won't work
});
// no return statement, that implicitly means `return undefined`
};
Now, why the #RocKhalil's answer, kind of, works:
async updateContainers() {
const response = await axios.get('/docker/containers')
// he favors a much clearer syntax of async/await
...
const containers = await this.updateContainer(filteredContainers)
this.setState({ containers });
};
async updateContainer(containers) {
return containers.map(async (container) => {
if (container.watcher) {
const response = await axios.get('/docker/containers/' + container.id)
// Because `axios.get()` was **awaited**,
// you can be sure that all code after this line
// executed when the request ended
// while this
// axios.get(...).then(() => console.log(2)); console.log(1)
// will lead to output 1 2, not 2 1
return {
...response.data,
id: container.id,
watcher: true,
}
} else {
return container;
}
});
// he does not forget to return the result of `map()`
// and `map()` in contrast with `forEach()` does have a result
// But...
}
But...
containers.map() returns an array. An array of Promises. Not a single Promise. And that means that
const containers = await this.updateContainer(filteredContainers)
waits for nothing. And updateContainer() function is not actually async.
To fix that you need to use Promise.all():
const containers = await Promise.all(this.updateContainer(filteredContainers))

How to Verify if each element the Array contains the search string in Typescript/protractor

How do i Verify if each element of the Array contains the search string in Typescript/ Protractor??
All the console statements returned false as they were looking for complete text rather than a search string. Please suggest a solution.
arr = [ 'Citibank, N.A.', 'Citi China Companies', 'Citibank Ireland' ]
search string = 'citi'
Then('I enter search text where the highlighted search results will include a Client Company Name {string}, {string}', async (searchText, companyName) => {
await acctmgrclientselection.deleteSearchText().then(async () => {
await acctmgrclientselection.getSelectClientSearchInputEl().sendKeys(searchText).then(async () => {
await acctmgrclientselection.getSelectClientSearchInputEl().sendKeys(protractor.Key.ENTER).then(async () => {
await dashboardFilter.getEmployeeListGrid().count().then( async ( CountVal ) => {
if(CountVal >1)
{
var strArr: Array<string> = [];
await acctmgrclientselection.getClientTblCompanyName().getText().then(async (text) => {
await strArr.push(text)
//strArr.forEach(function(value){
var sortable = [];
strArr.forEach(value => {
sortable.push([value]);
let sorted_array: Array<string> = sortable.map(arr => arr[0])
let result = sorted_array.every(element => element.includes(searchText))
console.log(result)
});
});
}
else
{
//clear criteria
console.log('clear criteria');
await element(by.cssContainingText('mat-card.empty-results.mat-card p','0 results matching your criteria')).isDisplayed().then(async()=>{
await element(by.cssContainingText('mat-card.empty-results.mat-card a','Clear Criteria')).isDisplayed();
});
}
});
});
});
});
});
You need to check for the regex with search string.
const pattern = new RegExp("Citi");
const result = sorted_array.every(element => pattern.test(element));
console.log(result);

Promise chaining not returning expected result

I have to send an e-mail for some users. I have a promise that returns the users Ids and another that returns the users e-mails (based on user id).
I have all of this chained but my parent function get an empty array.
I tried promises and async await but i have little experience with this and i dont know where im missing.
private async _getUserFromContatos(_subtipoEmergenciaID: number):Promise<string[]>{
const _arrTo: string[] = [];
sp.web.lists.getByTitle("Contato").items.get().then((items:any[]) => {
let _contatos = items.filter((i) => i.SubtipoEmergenciaId == _subtipoEmergenciaID);
_contatos.map(c => {
sp.web.getUserById(c.FuncionarioId).get().then(_userInfo => {
_arrTo.push(_userInfo.Email);
});
});
});
return _arrTo;
}
private _sendMail(){
this._getUserFromContatos(this.state.selectedSubtipoEmergencia).then(
_arrTo => {
console.log(_arrTo); //Returns the array as if its filled ok
console.log(_arrTo.length); //Returns 0 (empty array)
});
}
The first console.log at the end return the array filled but the second one returns 0.
I cant access the array items.
Your problem is that the array is not guaranteed to be filled when the first function returns. That is because you never await the result of the getUserById call.
Here are two possible solutions (one using await / one without await)
function _getUserFromContatos(_subtipoEmergenciaID: number): Promise<string[]> {
return sp.web.lists
.getByTitle("Contato")
.items
.get()
.then((items: any[]) => {
let _contatos = items.filter(i => i.SubtipoEmergenciaId == _subtipoEmergenciaID);
return Promise.all(
_contatos.map(c => {
sp.web
.getUserById(c.FuncionarioId)
.get()
.then(_userInfo => _userInfo.Email);
})
);
});
}
async function _getUserFromContatos(_subtipoEmergenciaID: number): Promise<string[]> {
var items = await sp.web.lists.getByTitle("Contato").items.get(); // await the list
let _contatos = items.filter(i => i.SubtipoEmergenciaId == _subtipoEmergenciaID);
var _arrTo: string[] = [];
for (var c of _contatos) {
var userInfo = await sp.web.getUserById(c.FuncionarioId).get(); // query every user and await that result
_arrTo.push(userInfo.Email);
}
return _arrTo;
}
function _sendMail() {
this._getUserFromContatos(this.state.selectedSubtipoEmergencia).then(
_arrTo => {
console.log(_arrTo); //Returns the array as if its filled ok
console.log(_arrTo.length); //Returns 0 (empty array)
}
);
}

Parsing firebase query data in reactjs

I am using firebase cloud firestore for storing data. And I am developing a web app using reactjs. I have obtained documents using the following function:
getPeoples() {
let persons = [];
firestore.collection("students")
.get()
.then(function (querySnapshot) {
querySnapshot.forEach((doc) => {
var person = {};
person.name = doc.data().Name;
person.course = doc.data().Course;
persons.push(person);
})
});
console.log(persons);
return persons;
}
I am getting the desired data, but when I am iterating through persons array, it says it has length of 0.
here is the console output when I am displaying complete persons array and its length.
The length should be 14, but it shows 0. Please correct me what is wrong with me?
I want to display the output in the html inside the render() method of react component.
The output of
const peoples = this.getPeoples();
console.log(peoples);
It is:
The complete render method looks like:
render() {
const peoples = this.getPeoples();
console.log(peoples);
return (
<div className="peopleContainer">
<h2>Post-Graduate Students</h2>
{/* <h4>{displayPerson}</h4> */}
</div>
);
}
This is due to the fact the query to the database is asynchronous and you are returning the persons array before this asynchronous task is finished (i.e. before the promise returned by the get() method resolves).
You should return the persons array within the then(), as follows:
getPeoples() {
let persons = [];
return firestore.collection("students")
.get()
.then(function (querySnapshot) {
querySnapshot.forEach((doc) => {
var person = {};
person.name = doc.data().Name;
person.course = doc.data().Course;
persons.push(person);
})
console.log(persons);
return persons;
});
}
And you need to call it as follows, because it will return a promise :
getPeoples().then(result => {
console.log(result);
});
Have a look at what is written to the console if you do:
console.log(getPeoples());
getPeoples().then(result => {
console.log(result);
});
I'm not sure but please try to update your
getPeoples() {
let persons = [];
firestore.collection("students")
.get()
.then(function (querySnapshot) {
querySnapshot.forEach((doc) => {
var person = {};
person.name = doc.data().Name;
person.course = doc.data().Course;
persons.push(person);
})
});
console.log(persons);
return persons;
}
to
getPeoples() {
let persons = [];
firestore.collection("students")
.get()
.then(querySnapshot => {
querySnapshot.forEach((doc) => {
persons.push({name = doc.data().Name,
course = doc.data().Course
})
});
console.log(persons);
return persons;
}
Update
Sorry I thought you have problem with filling persons array in your function. Anyway as Renaud mentioned the query in your function is asynchronous so the result is not quick enough to be displayed on render. I use similar function and I found redux the best way to handle this situations.

Resources