-1

I have an object array in my state

Expenses = [{title: 'Dubai Trip', category: 'Travel', date:'2022-11-06T19:29:29.000+00:00' ,amount: 50000},
            {title: 'Laptop', category: 'Shopping', date: '2022-10-31T19:30:41.000+00:00', amount: 30000},
            {title: 'McDonalds', category: 'Food', date: '2022-10-07T09:50:25.000+00:00', amount: 300}]

I didn't actually declared it myself, I initiallized and empty array in my state and retrieved it from an API request

constructor(props){
        super(props)

        this.state = {
            Expenses: []
        }  
    }


componentDidMount(){

UserService.getExpense(userId).then((res) =>{
            this.setState({ Expenses:res.data});
        });
this.setState({Expenses: this.state.Expenses.map(expense =>{ return{...expense,date: new Date(expense.date)};})});
}

As you can see that the values of date are in string format I am trying to change the into Date() format but they do not change.

I also tried doing

this.setState({Expenses: this.state.Expenses.map(expense =>{ return{...expense,amount: expense.amount*2};})});

But it does not reflects

Faraz
  • 1
  • 1
  • replace the `setState` inside the `then` callback with the setState with `map` logic. Use `res.data.map(...)` – adiga Nov 08 '22 at 08:24
  • Does this answer your question? [map function for objects (instead of arrays)](https://stackoverflow.com/questions/14810506/map-function-for-objects-instead-of-arrays) – Jay Nov 08 '22 at 08:29

1 Answers1

0

It will not affect since this.state.Expenses is empty you need to manipulate then setState as below.

componentDidMount(){
  UserService.getExpense(userId).then((res) => {
    this.setState({
      Expenses: res.data.map((expense) => {
        return { ...expense, date: new Date(expense.date) };
      }),
    });
  });
}
Elvin
  • 565
  • 1
  • 5
  • 12