how to wait until value assigned in react

I’m new in React framework and I’m facing following issue: When I’m trying to call backend api after assigning some values, the api is called before the assigned values are updated in the state.

Let me show you the code to get a better understanding:

  // define state in RFC 
  const [item, setItem] = useState("");


  // get value when user click submit button
  const itemInputOnClickHandler = ()=> {
  let comingItemValue = document.getElementById('item-input').value;
  setItem(comingItemValue);
  submitHandler();
  }


  // call api
  const submitHandler = async() => {
  await axios.post("API_URL");
  }



  // button in html:
  <Button label="submit" onClick={itemInputOnClickHandler} className="m-3 btn" />

I tried many aproaches but still get the same result: The api is called before the assigned values are updated in the state.

How can I solve this so the api is called after the state has been updated?

>Solution :

Best not to use DOM functions directly, it’s better to store the input value in some sort of state as the user is changing the value, then when it comes to submitting, the value is already available

try something like the following –

// define state in RFC 
const [item, setItem] = useState("");
const [inputValue, setInputValue] = useState("");

const onInputChange = (e) => {
    setInputValue(e.target.value)
}


// get value when user click submit button
// this is a bit redundant now, you could call submitHandler directly as the onClick handler
const itemInputOnClickHandler = ()=> {
  submitHandler();
}


// call api
const submitHandler = async() => {
  // inputValue is available here to post
  await axios.post("API_URL");
}

// your text input field
<input onChange={onInputChange} ... />

// button in html:
<Button label="submit" onClick={itemInputOnClickHandler} className="m-3 btn" />

As a side note though, the issue you are running into is that setting state is async therefore calling setItem(x) does not set set the value immediately, it would be available in the next render, therefor your API function is grabbing the old value.

Leave a Reply