React state clearing onChange

Issue

i am trying to build a calculation platform and i got an issue in that process when i am trying to clearing the state of my input value its last value store in it and because of that i am not able to perform certain task here the code

import React, { useState } from "react";

const App = () => {
const [buyPrice, setBuyPrice] = useState(8000);
const [buyAMount, setBuyAMount] = useState(0);
const [buy_total, setBuy_total] = useState(0);

const handleBuyChange = (e) => {
  var { name, value } = e.target;
  if (name == 'buyPrice') {
    setBuyPrice(value);
  }
  if (name == 'buyAMount') {
    setBuyAMount(value);
  }
  if (name == 'buy_total') {
    setBuy_total(value);
  }
  console.log('alert',buyPrice,buyAMount,buy_total)
};

return (
  <div>
    <div>
      <input
        type={"number"}
        name="buyPrice"
        value={buyPrice}
        onChange={(e) => handleBuyChange(e)}
      />
      <input
        type={"number"}
        name="buyAMount"
        value={buyAMount}
        onChange={handleBuyChange}
      />
      <input
        type={"number"}
        name="buy_total"
        value={buy_total}
        onChange={handleBuyChange}
      />
    </div>
  
  </div>
);
};

Heres the console:–
img

Solution

React setState functions are asynchronous in nature so the console.log showing previous values might be due to the fact that the state hasn’t been updated yet so if you perform console.log outside the function you will get the updated values

import React, { useState } from "react";

const App = () => {
const [buyPrice, setBuyPrice] = useState(8000);
const [buyAMount, setBuyAMount] = useState(0);
const [buy_total, setBuy_total] = useState(0);

const handleBuyChange = (e) => {
  var { name, value } = e.target;
  if (name == 'buyPrice') {
    setBuyPrice(value);
  }
  if (name == 'buyAMount') {
    setBuyAMount(value);
  }
  if (name == 'buy_total') {
    setBuy_total(value);
  }
  
};

console.log('alert',buyPrice,buyAMount,buy_total)

return (
  <div>
    <div>
      <input
        type={"number"}
        name="buyPrice"
        value={buyPrice}
        onChange={(e) => handleBuyChange(e)}
      />
      <input
        type={"number"}
        name="buyAMount"
        value={buyAMount}
        onChange={handleBuyChange}
      />
      <input
        type={"number"}
        name="buy_total"
        value={buy_total}
        onChange={handleBuyChange}
      />
    </div>
  
  </div>
);
};

Answered By – Kushal Raut

Answer Checked By – Mildred Charles (AngularFixing Admin)

Leave a Reply

Your email address will not be published.