1

There is ONE input element, whose value is given by the user. and 3 buttons, whose values are coming from the states.

So when I put intput value as "11" and press SUBMIT1 button, then the output in console should be {userId: "11", submit1: "1"}

Instead I get the whole submit values too

{userId: "11", submit1: "1", submit2: "2", submit3: "3"}

Also, I got a response error (LINE NUMBER 23) : I am trying to send one INPUT value and ONE submit value (of the button that was clicked..)

PostForm.jsx file

import React, { Component } from "react";
import axios from "axios";
class PostForm extends Component {
  constructor(props) {
    super(props);

    this.state = {
      userId: "",
      submit1: "1",
      submit2: "2",
      submit3: "3"
    };
  }

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

  submitHandler = e => {
    e.preventDefault();
    console.log(this.state);
    axios
      .post(
        "https://jsonplaceholder.typicode.com/posts/${userId}/${submit}",
        this.state
      )
      .then(response => {
        console.log(response);
      })
      .catch(error => {
        console.log(error);
      });
  };

  render() {
    const { userId, submit1, submit2, submit3 } = this.state;
    return (
      <div>
        <form onSubmit={this.submitHandler}>
          <div>
            <input
              type="text"
              name="userId"
              value={userId}
              onChange={this.changeHandler}
            />
          </div>

          <button value={submit1} onChange={this.changeHandler} type="submit">
            Submit1
          </button>
          <button value={submit2} onChange={this.changeHandler} type="submit">
            Submit2
          </button>
          <button value={submit3} onChange={this.changeHandler} type="submit">
            Submit3
          </button>
        </form>
      </div>
    );
  }
}

export default PostForm;

https://codesandbox.io/s/vigorous-ptolemy-p1s4i

2
  • 1
    Hi, i post an answer to your question, let me know if you have any other issue or if your problem was solved Commented May 20, 2020 at 14:19
  • Hey, thank you so much for answering, really appreciate it Commented May 20, 2020 at 16:47

1 Answer 1

4

You need to call the submit method from the onClick method of each submit button, also you had an issue in your jsonplaceholder : you dont need to send the whole route in POST method....just the payload is enough

Also, you do not need the onChange method on a button....i removed them.

import React, { Component } from "react";
import axios from "axios";
class PostForm extends Component {
  constructor(props) {
    super(props);

    this.state = {
      userId: "",
      submit1: "1",
      submit2: "2",
      submit3: "3"
    };
  }

  buildPayload = submitName => {
    return { [`submit${submitName}`]: submitName, userId: this.state.userId };
  };

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

  submitHandler = (submitName) => {
    const payload = this.buildPayload(submitName);
    console.log(payload);
    axios
      .post(`https://jsonplaceholder.typicode.com/posts`, payload)
      .then(response => {
        console.log(response);
        // If you need the data here so do the following
        console.log(response.data)
      })
      .catch(error => {
        console.log(error);
      });
  };

  render() {
    const { userId, submit1, submit2, submit3 } = this.state;
    return (
      <div>
        <form onSubmit={e => e.preventDefault()}>
          <div>
            <input
              type="text"
              name="userId"
              value={userId}
              onChange={this.changeHandler}
            />
          </div>

          <button
            value={submit1}
            onClick={() => this.submitHandler(this.state.submit1)}
          >
            Submit1
          </button>
          <button
            value={submit2}
            onClick={() => this.submitHandler(this.state.submit2)}
          >
            Submit2
          </button>
          <button
            value={submit3}
            onClick={() => this.submitHandler(this.state.submit3)}
          >
            Submit3
          </button>
        </form>
      </div>
    );
  }
}

export default PostForm;

Output (in console) :

{userId: "11", submit1: "1"} 

In the console

example

Now if you want, you can also refactor the submit method to an async one....just to make it cleaner :

  submitHandler = async (submitName) => {
     const payload = this.buildPayload(submitName);
     const response = await axios.post(`https://jsonplaceholder.typicode.com/posts`, payload)
     console.log(response.data);
  };
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for the answer :D could you please ans this question too stackoverflow.com/questions/61918624/… , it's regarding the same problem
I am not able to send my data in the format of payload post(https://jsonplaceholder.typicode.com/posts, payload), this is not working for me, also I need to PUT and not post....can you please tell me how to do it in this format "jsonplaceholder.typicode.com/posts?loadId=${this.userId}&eventName=${this.eventName}
I am using some other api actually, its a PUT api, i cant share it here due to confidentiality reasons...so suppose i had a url like that, and i needed to make a PUT req, how would i send the loadId and eventName to it
I answer to this question in your second post....please see there and let me know
would you please update solution for functional component? Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.