1

Hi i am new to react js i am calling getItem function and pushing response to an array and return array that array but i am getting empty array before i return

  private _LoadExpenses() {
    const items: IExpense[] = [];
    this._expensesDataProvider.getItems().then((expenses: IExpense[]) => {
        expenses.forEach(element => {
          items.push({SGDDAppDate:element.SGDDAppDate,ExpenseCategory:element.ExpenseCategory,ExpenseType1:element.ExpenseType1});
       });
        return expenses;
    });
    //console.log(items)
    return items;
  }
Rana Umair
  • 21
  • 1
  • 6
  • expenses array must be empty, that's why forEach is not executing therefore the empty array – kooskoos Dec 10 '19 at 07:24
  • 2
    Is _expensesDataProvider.getItems() is async ? If so you should have some kind of await statement there. Additionally I would use rather state of the component instead of directly returning the array. – Maciej Trojniarz Dec 10 '19 at 07:36

2 Answers2

1

after Block this._expensesDataProvider finished You console.log(items) which it must be empty. and i'm think getItems() is async so before data arrives and items are pushed in the items array you console.log the items which is empty.

you need to console.log(items) before return expenses;

and if you need to return Items for later User u can wrapp your code in Promise and return a Promise , then each time you need items you have to use .then like this example => https://codesandbox.io/s/kind-rhodes-w1twf

because as soon as "this._expensesDataProvider" runs then "return items" is going to run and at this time items are empty.

Amir Rezvani
  • 1,262
  • 11
  • 34
  • Thanks for your response. yes i am getting before return expenses but after then() its empty. i need to return items – Rana Umair Dec 10 '19 at 07:47
0

My sample async function code:

private async _getListData(): Promise<IReactItem[]> {
  return pnp.sp.web.lists.getByTitle("TestList").items.select("Id,Title,Description,User/ID,User/EMail").expand("User").get().then((response:IReactItem[]) => {
    return response;
  });
}

Call the function:

this._getListData().then(items=>{
    console.log(items);
  });

For your code.

Try:

private _LoadExpenses(): Promise<IExpense[]> {  
  return this._expensesDataProvider.getItems().then((expenses: IExpense[]) => {      
      return expenses;
  });  
}
Lee
  • 5,305
  • 1
  • 6
  • 12