Ubaid Parvaiiz
Ubaid Parvaiiz

Reputation: 105

How to update an item in the state after the previous values of the state get updated?

I was building a react price tracking app which will take all of your expenses,income and then list them.

I had to update the budget after the item has been added either to the expense or an income but because of the async nature of the setState it's not working properly?

Here's my function

async create(e){
        e.preventDefault()
        var type = this.type.value
        var obj  = {'id':this.NextId(type),'description':this.description.value,'amount':this.amount.value}
        if (type ==="expense"){
            obj.percentage   = "%100"

            var newState = this.state.setState((prevState)=>({
                expense:[...prevState.expense,obj],
                totalExpense:prevState.budget - parseInt(this.amount.value)
            }))
        }
        else{
            var newState = this.state.setState((prevState)=>({
                income:[...prevState.income,obj],
                totalIncome:prevState.totalIncome + parseInt(this.amount.value)

            }))
        }


        this.state.setState({budget:this.state.totalIncome  - this.state.totalExpense,percentage:this.getPercentage()}))        
    }

Upvotes: 0

Views: 42

Answers (2)

Ubaid Parvaiiz
Ubaid Parvaiiz

Reputation: 105

I made a new function which treated the setState as a Promise

async PromiseSate(state){
       await new Promise(resolve => this.setState(state,resolve))
    }
var exampleSetState = PromiseState({data:"data"})

Then you could do like this

exampleSetState.then("your code goes here")

Upvotes: 0

Sumanth Madishetty
Sumanth Madishetty

Reputation: 3605

You can use setState callback in your case,

For example lets say you want to update budget after the expense is updated you can pass a function as callback for setState

this.setState(prevState => ({ expense: prevState.expense -10   }), () => {
  this.setState(prevState => ({ budget: prevState.totalIncome - prevState.expense }))
})

Or you can update multiple items at the same time

this.setState(prevState => ({ expense: prevState.expense -10, budget: prevState.budget - 10 }))

Upvotes: 1

Related Questions