0

I must post {input} data to http://localhost:4000/prediction with Axios. But {input} turns undefined.

I am using const instead of class Main extends component. onChange, it sets form data.

const Main = ({ value, suggestions, auth: { user } }) => {

  const [formData, setFormData] = useState("");

  const [messages, setMessages] = useState([]);

  const { input } = formData;

  const onChange = e => setFormData(e.target.value);

  const onSubmit = event => {
    event.preventDefault();
    setMessages(prevMsgs => [...prevMsgs, formData]);

    console.log({ input });

Axios post.

    axios
      .post(
        `http://localhost:4000/prediction`,
        { input },
        { crossdomain: true }
      )
      .then(res => {
        console.log(res.data);
        //setMessages(prevMsgs => [...prevMsgs, formData]);
      })
      .catch(error => {
        console.log(error.message);
      });
  };

Return (form) with onSubmit, onChange.

  return (
    <div className="true">
      <br />
      <form noValidate onSubmit={e => onSubmit(e)}>
        <div className="input-group mb-3">
           <input
                name="input"
                type="text"
                className="form-control"
                placeholder="Type text"
                onChange={e => onChange(e)}
              />
            )}
          <div className="input-group-append">
            <button className="btn btn-outline-secondary">Send</button>
          </div>
        </div>
      </form>
    </div>
  );
};
1
  • formData is a string as I see which does not have a property called input what you try to destructure. Commented Feb 16, 2020 at 19:46

1 Answer 1

2

As I have mentioned in the comment section formData is a string as I see which does not have a property called input what you try to destructure and that's why it is undefined always.

If you really need that format for axios then you can try change the structure of formData with useState as the following first:

const [formData, setFormData] = useState({input: null});

Then maybe you can try updating as:

const onChange = e => setFormData({input: e.target.value});

I hope that helps!

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, but one more thing. Can't we really make the input "form data"? How can I set {input} to form data? const data = new FormData(); data.set("input", { input }); didn't work well.

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.