Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

192
Views
fetch api happens before I submit the form

I use react js as frontend framework and laravel as backend framework. I also use proxy. I have a function that hanlde submit of my form. Everytime I load my form page I got two responses on my console although I haven't hit the submit button yet. This is my component CreateDaerah. I use function component

import React, { useEffect, useState} from 'react';

const CreateDaerah = () => {
    const [nama, setNama] = useState('');

    const handleSubmit = (url = '', data = {}) => {
        fetch(url, {
            method: "POST",
            body: JSON.stringify(data),
            headers: {
                'Content-Type': 'application/json'
            }
        })
        .then(response => console.log(response))
        .catch(err => console.error(err));;
    }
    

    return(
        <div className="card-create">
            <form onSubmit={handleSubmit(`/api/provinsi`, nama)}>
                <h1>Form Provinsi</h1>
                <label htmlFor="nama">Nama</label>
                <input type="text" 
                        className="nama-provinsi" 
                        name="nama" 
                        placeholder="masukkan nama"
                />
                <button type="submit">Submit</button>
            </form>
        </div>
    );
}

Also how can I get the nama value from the input? Should I use onChange attribute?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

This is because you are calling handleSubmit immediately at each render rather than providing a function to be called at submit. Instead you should update it to something like:

import React, { useEffect, useState} from 'react';

const CreateDaerah = () => {
    const [nama, setNama] = useState('');

    const handleSubmit = (url = '', data = {}) => {
        fetch(url, {
            method: "POST",
            body: JSON.stringify(data),
            headers: {
                'Content-Type': 'application/json'
            }
        })
        .then(response => console.log(response))
        .catch(err => console.error(err));;
    }
    

    return(
        <div className="card-create">
            <form onSubmit={() => handleSubmit(`/api/provinsi`, nama)}>
                <h1>Form Provinsi</h1>
                <label htmlFor="nama">Nama</label>
                <input type="text" 
                        className="nama-provinsi" 
                        name="nama" 
                        placeholder="masukkan nama"
                />
                <button type="submit">Submit</button>
            </form>
        </div>
    );
}
about 4 years ago · Juan Pablo Isaza Report

0

  1. You're calling the handleSubmit function immediately on the render, so you either need to pass a reference to the function instead with a callback, or just pass the function reference without those arguments.

  2. I probably wouldn't pass those arguments. I wouldn't even use a form element as elements don't need to be wrapped in it. I'd would declare the URL in the component and place the handleSubmit on the button. That way you don't have to deal with the form updating the page.

  3. Place an onChange handler on your input which calls a function that updates the state, and have the value of that input be the result of the state.

Here's a shorter working example.

const { useState } = React;

function Example() {

  const [ numa, setNuma ] = useState('');

  const url = `/api/provinsi`;

  function handleInput(e) {
    setNuma(e.target.value);
  }

  function handleClick() {
    console.log('Button clicked');
    console.log(`Final state: ${numa}`);
    // fetch(url) using numa state
  }

  return (
    <div>
      <input value={numa} onChange={handleInput} />
      <button onClick={handleClick}>Click me</button>
    </div>
  );
};

// Render it
ReactDOM.render(
  <Example />,
  document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!