Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

193
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda