Jenil Chavda
Jenil Chavda

Reputation: 93

How to make addition of state in react native

I want to addition of two state,

the both value of state are extracted from json object using a fetch request

 constructor(props) {
    super(props);
    this.state = {
     charge:0,
     total:0,
    };
  }

 dataFatch()
  {    
  const tot =  this.state.total;        
                fetch('https://xyz.in/app/reg.php', {
                method: 'POST',
                mode: 'no-cors',
                headers: {
                  'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                  'item_id':ids,
                  'func':'item_data',
                })
              }).then((response) => response.json())
              .then((json) => {

                  this.setState({'total':json.total});
                  this.setState({'charge':json.charge}); 

              }).catch((err) => { console.log(err); });
  }

but after a fetching data charge=30 and total=80

i preform addition like

Let add = this.state.charge+this.state.total;
console.log(add);

but the result is 3080 instead of 110

so how can i solve this problem

Upvotes: 2

Views: 689

Answers (1)

It looks like an you are doing concat strings instead of number

I don't see add logic in your api request function but as per you showed you can fix it with below

let add = Number(this.state.charge) + Number(this.state.total);
console.log(add);

But important is you understand that the state you stored isn't number but typeof string.

So while updating state you can make sure it's number not an string so you don't need to convert it into number while doing concat.

Upvotes: 4

Related Questions