zicxor
zicxor

Reputation: 57

React Axios Input Undefined

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>
  );
};

Upvotes: 0

Views: 295

Answers (1)

norbitrial
norbitrial

Reputation: 15166

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!

Upvotes: 2

Related Questions