reactjs

Request to API is not sent


I can't send a request to an API from a React form.

I have the following code:

function App() {

  function calculate(){

   console.log("test");
   alert('test');
   const requestOptions = {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ "localSalesCount": 50, "foreignSalesCount":50, "averageSaleAmount":200 })
    };
    fetch('https://localhost:5000/Commision', requestOptions)
        .then(response => response.json())
        .then(data => this.setState({ totalFcamaraCommission: data.totalFcamaraCommission }));

}

  const totalFcamaraCommission = 50;
  const totalCompetitorCommission = 10;
  return (
    <div className="App">
      <header className="App-header">
        <div>
        </div>
        <form action={calculate}>
          <label for="localSalesCount">Local Sales Count</label>  
          <input name="localSalesCount" /><br />

          <label for="foreignSalesCount">Foreign Sales Count</label>  
          <input name="foreignSalesCount" /><br />
          
          <label for="averageSaleAmount">Average Sale Amount</label>  
          <input name="averageSaleAmount" /><br />

          <button type="submit">Calculate</button>
        </form>
      </header>

      <div>
        <h3>Results</h3>
        <p>Total FCamara commission: {totalFcamaraCommission}</p>
        <p>Total FCamara commission: {totalCompetitorCommission}</p>
      </div>
    </div>
  );
}

the main problem is that console.log or alert are not executed, so there is something wrong with the code, because the function is not being called.


Solution

  • As @0stone0 pointed out in the comments, it looks like the action is refreshing the page before calling the function.

    Also, it might be necessary to add event.preventDefault() to your calculate() method so it executes and not refreshes the page.

    Something like:

    function calculate(event){
        event.preventDefault();
        ...
    }