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

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

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 Denunciar

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 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