title: React Hooks: updating state using useState does not update the state immediately
body: <p>I have a form that has various fields, and one of the fields contains an array of objects.</p>
  
  <p>It pretty much adds an object that contains values from a subform of the main form.</p>
  
  <pre><code>const addNode = () =&gt; {
      let p_form = pForm
      let ha = [vForm, yForm, hForm]
      let info = [....]
      setCurrentNodeForm(
          {
              ...currentNodeForm,
              p: p_form,
              ha: ha,
              info: info,
          }
      )
      // inserts this form to a state called `addedNodes`
      let currArr = [...addedNodes]
      currArr.push(currentNodeForm)
      setAddedNodes(currArr)
      intializeForms()
  }
  </code></pre>
  
  <p>This is the function that I use as an <code>onClick</code> function of my <code>Add</code> button.</p>
  
  <p>This adds a new object to a state called <code>addedNodes</code> which is an array of objects.</p>
  
  <p>Then when I submit my main form, I use the function below as an <code>onClick</code> function</p>
  
  <pre><code>const submitMainForm = () =&gt; {
      let credentials = [...]
      let nodes = [...addedNodes]
      setMainForm(
          {
              ...currentMainForm,
              credentials: credentials,
              nodes: nodes,
          }
      )
  
      let body = {
          name: .... // something
          objects: currentMainForm,
      }
  
      intializeForms()
  
      let options = {
          headers: header,
          method: 'post',
          mode: 'cors',
          body: JSON.stringify(body),
      }
  
      console.log('options.body', options.body)
  
      return new Promise((resolve, reject) =&gt; {
          fetch(endpoint, options)
              .then(res =&gt; res.json())
              .then(resText =&gt; {
                  console.log('resText', resText)
              })
      }).catch(err =&gt; {
          console.log(err)
      })
  }
  </code></pre>
  
  <p>What it does is, it updates the state <code>currentMainForm</code> using the current <code>addedNodes</code> object array that I have updated using the <code>addNode</code> function above. However, when I <code>console.log</code> the <code>options.body</code> as shown above, the <code>objects</code> field in the <code>body</code> is empty. Thus, when I send a <code>POST</code> request, the <code>body</code> is missing its critical part.</p>
  
  <p>When I <code>console.log</code> the same thing outside the function, it shows up. </p>
  
  <p>I wonder how I can guarantee the state to be updated properly inside the function.</p>
  
  <p>Thanks in advance.</p>