Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

158
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!