0

I am trying to pass the updated value through convert function to display the new result on every state update but it seems the states "const [values]" is not updating immediately and I am getting results from previous state value. So with every value change my results are a step behind. In the console I can see I am getting new value from the input but the "values" state shows previous values.

const [values, setValues] = useState({
        sqmtr: "",
        sqft: "",
    });
  
  const handleTextChange = (text, name) => {
        setValues({ ...values, [name]: text });
        convert(unit, values);
                console.log(text);
                console.log(values);
    };
<TextInput
  style={styles.inputField}
  defaultValue={values.sqmtr}
  onChangeText={(text) =>
    handleTextChange(text, "sqmtr")}
  placeholder="0"
  keyboardType={"numeric"}
/>
Prajwal
  • 3
  • 3
  • Please dont reply on console.log to determine the state update , since it is async process . If you want to see whether state is updating or not , you can use , useEffect() hook – Harmandeep Singh Kalsi Aug 26 '20 at 15:10
  • 1
    @HarmandeepSinghKalsi, you're almost right, but it's not that React may update or may not update, React will never update immediately because setState is async. – Piotr Białek Aug 26 '20 at 15:13
  • Does this answer your question? [useState set method not reflecting change immediately](https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately) – Harmandeep Singh Kalsi Aug 26 '20 at 15:15
  • You can use `useEffect` to catch changes for example for `values` as `useEffect(() => { console.log(values) }, [values])`. Read further about `useEffect` [here in the documentation](https://reactjs.org/docs/hooks-effect.html). – norbitrial Aug 26 '20 at 15:44

2 Answers2

0

It works fine, because setState is asynchronous. New set value will be seen in a new component render.

Piotr Białek
  • 2,569
  • 1
  • 17
  • 26
0
const handleTextChange = (text, name) => {
  const value = { ...values, [name]: text }
  // `setValues` is async. so use the value directly
  setValues(value);
  convert(unit, value);
  console.log(text);
  console.log(values);
};
Liu Lei
  • 1,256
  • 1
  • 9
  • 18