title: React wait for function to finish?
body: <p>I want to create a form where I type some data (barcode and name) and if an object with this data exists in my Products table I set states and save it in another Stocks table. But I have a problem when an objects doesn't exist. First I want to post it to a Products table and then to a target table. When I set product_id it is only visible in my saveProduct function and object is added to Stocks with id one down.
  I tried also setting id in saveStocks() but it doesn't work because it is called before Products table is updated.
  How to wait for it to finish? Or how to set id properly?</p>
  <pre><code>const saveProducts = () =&gt; {
      var data = {
        barcode: barcode,
        name: name,
      };
  
      axiosInstance.post('/products/', data)
        .then(response =&gt; {
          setBarcode(response.data.barcode);
          setName(response.data.name);
          setProductId(response.data.product_id) //doesn't update in second function
  
        })
        .catch(e =&gt; {
          console.log(e);
        });
    }
    
    const saveStock = () =&gt; {
      const temp = products.filter(product =&gt; product.barcode == barcode)
      if (!temp.length) {
        saveProducts()
        getProducts()
        setProductId(products[products.length-1].product_id) //called before saveProducts()
      }
      setTimeout(() =&gt; {
        var data = {
          stock_id: stock_id,
          product_id: product_id,
          count: count,
        };
        axiosInstance.post('/stocks/', data)
          .then(response =&gt; {
            setStockId(response.data.stock_id);
            setProductId(response.data.product_id);
            setCount(response.data.count);
          })
          .catch(e =&gt; {
            console.log(e);
          });
      }, 2000)
    }
  </code></pre>
  <p>I call saveStock() when clicking the button under my form:</p>
  <pre><code>&lt;button className=&quot;btn btn-success&quot; type=&quot;button&quot; onClick={saveStock}&gt;Add&lt;/button&gt;
  </code></pre>