0

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?

iLuvLogix
  • 5,920
  • 3
  • 26
  • 43
MoSaleh
  • 23
  • 1
  • 7

2 Answers2

0

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.

andy mccullough
  • 9,070
  • 6
  • 32
  • 55
0

In react the state changes do not occur right after. The setState of react is async. It does this because it is an expensive operation and chooses to do many state updates at once to increase efficiency.

If you would like to call the API after the state has been changed , I would suggest adding a callback to the state change and executing the API in the callback function.

Use the useCallback() hook and add the state as a dependency array to execute on every state change.