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

160
Visualizações
Passing a state for an Axios POST request

I want to pass a state into an axios post request, for the state data to get into my backend. But i get an error telling me the state that i chose is not defined.

Here's what i've got:

React frontend

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

class Gluecksrad extends Component {
  constructor(props) {
    super(props);
    
    this.state = {
      spieler: "",
    };
  }

  submitName() {
    const body = { spieler: this.state.spieler };
    Axios.post("http://localhost:3001/api/insert", body).then(() => {
      console.log(this.state.spieler);
      alert("successful insert");
    });
  }

  render() {
    return (
      <React.Fragment>
        <h1>Glücksrad</h1>
        <label htmlFor="name">Name</label>
        <input
          id="name"
          type="text"
          onChange={(e) => {
            this.setState({ spieler: e.target.value });
            console.log(this.state.spieler);
          }}
        ></input>
        <button onClick={this.submitName}>Name Absenden</button>
      </React.Fragment>
    );
  }
}

export default Gluecksrad;

Node Backend

app.use(express.json());
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));

app.post("/api/insert", (req, res) => {
  const spieler = req.body.spieler;

  const sqlInsert = "INSERT INTO spiele (spieler) VALUES (?)";
  db.query(sqlInsert, spieler, (err, result) => {
    console.log(result);
  });
});

Here is the result

error

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

In your function submitName you are creating the body of the axios request using a variable spieler but it has not been defined previously. You should make use of spieler from state as follows:

submitName() {
  const body = { spieler: this.state.spieler };
  Axios.post("http://localhost:3001/api/insert", body).then(() => {
    console.log(this.state.spieler);
    alert("successful insert");
  });
}

Regarding your second problem of this.state being undefined, this results from the fact that by default, you can't access the surrounding context represented by the this keyword when using regular functions because they have their own context. Since you are indeed using a regular function submitName(), you need to bind this to it in order to access the context of the surrounding class. Alternatively, you can make use of an arrow function submitName = () => {} which doesn't need binding as it preserves the surrounding context. I've created this codesandbox for you which shows the two valid options as well as the wrong approach. Mind the console.log(this). It logs the Gluecksrad class for the arrow function or regular function with this binding while it logs undefined when submitting without this binding. Accessing the state property with this being undefined in the latter approach is the root of the error. You can read more about the reason for this binding in this article.

about 4 years ago · Juan Pablo Isaza Relatório

0

You have to bind your methode submitName by adding this line to your constructor. you can learn more about react forms from the official docs here

this.submitName = this.submitName.bind(this);

you constructorshould look like this:

constructor(props) {
    super(props);

    this.state = {
        spieler: "",
    };
    this.submitName = this.submitName.bind(this);
}

You are not accessing the real properties. replace

{
      spieler: spieler,
}

with

{
      spieler: this.state.spieler,
}
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