Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

194
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda