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

267
Visualizações
How to send POST and refresh page with React?

I have written a simple form that sends a post request with data to the server. On click of the submit button, I want to clear the form, so I create a function that refreshes the page. The function works correctly, but now the data is not sent to the server.

import React, {Component} from "react";
import axios from "axios";

class PostForm extends Component {

constructor(props) {
    super(props);
    this.state = {
        id: '',
        name: '',
        surname: '',
        country: ''
    }
}

changeHandler = e => {
    this.setState({[e.target.name]: e.target.value});
}

clearFunc = () => {
    window.location.reload(false);
}

submitHandler = e => {
    e.preventDefault();
    console.log(this.state);
    axios.post('http://localhost:8080/human/add/', this.state)
        .then(response => {
            console.log(response)
        })
        .catch(error => {
            console.log(error)
        });
}


render() {
    const {id, name, surname, country} = this.state;
    return (
        <div>
            <form id="input-form" onSubmit={() => {
                this.submitHandler();
                this.clearFunc()
            }}>
                <div>
                    <input type="number" name="id" value={id} onChange={this.changeHandler}/>
                </div>
                <div>
                    <input type="text" name="name" value={name} onChange={this.changeHandler}/>
                </div>
                <div>
                    <input type="text" name="surname" value={surname} onChange={this.changeHandler}/>
                </div>
                <div>
                    <input type="text" name="country" value={country} onChange={this.changeHandler}/>
                </div>
                <button type="submit">Submit</button>
            </form>
        </div>
    )
}
}

export default PostForm;
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

I would move this line this.clearFunc() inside submitHandler, in that then block, like so:

submitHandler = (e) => {
  e.preventDefault();
  console.log(this.state);
  axios
    .post("http://localhost:8080/human/add/", this.state)
    .then((response) => {
      console.log(response);
      this.clearFunc();
    })
    .catch((error) => {
      console.log(error);
    });
};

Also, if it's just to empty the form, there is no need to refresh the page, you could simply do so:

clearFunc = () => {
  this.setState({
    id: "",
    name: "",
    surname: "",
    country: "",
  });
};
about 4 years ago · Juan Pablo Isaza Relatório

0

It looks like you did it in the wrong flow. If you want to clear the form after submitting it, mostly in React App, you only need to set all states to empty string after the POST has succeeded (which means we will put it inside then()).

It would looks something like this:

clearForm = () => {
    // use this to reset the states
    this.setState({
        id: '',
        name: '',
        surname: '',
        country: ''
    })
}

submitHandler = e => {
    e.preventDefault();
    console.log(this.state);
    axios.post('http://localhost:8080/human/add/', this.state)
        .then(response => {
            console.log(response)
            clearForm() // <-- call the function here
        })
        .catch(error => {
            console.log(error)
        });
}

Why you should not put the clearForm() inside form onSubmit? Because we never know the POST request will succeeds or not. It's a good idea to keep the values is POST request has error response.

about 4 years ago · Juan Pablo Isaza Relatório

0

I don't think you need to refresh the page, as long as you are using the e.preventDefault() you are stopping the default behavior of refreshing the page by the form.

if all you want is to empty the form, then you can use the document.form.reset() where form is the name you have assigned to the form.

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