0

New to Reactjs. I'm trying to post data to a local server using axios, but it is returning an empty object. What am i doing wrong? I need to send a name and an email to the json file.

const FormNew = () => {
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");

  const handleChangeName = (event) => {
    setName(...name, { name: event.target.value });
  };

  const handleChangeEmail = (event) => {
    setEmail(...email, { email: event.target.value });
  };

  const handleSubmit = (event) => {
    event.preventDefault();

    axios
      .post("http://localhost:3002/posts", {
        name: name,
        email: email,
      })
      .then((res) => {
        console.log(res.data);
      });
  };

  return (
    <Form onSubmit={handleSubmit}>
      <Field.Text
        label="Name"
        name="name"
        type="text"
        onChange={handleChangeName}
      />
      <Field.Text
        label="Email"
        name="email"
        type="email"
        onChange={handleChangeEmail}
      />
      <Button type="submit">Submit</Button>
    </Form>
  );
};
export default FormNew;

Json file where i'm trying to send data.

{
  "posts": [
    {
      "name": "JSON SERVER",
      "email": "[email protected]",
      "id": 1
    }
  ]
}

9
  • We'll need the code on the receiving end of localhost:3002/posts to be able to tell what's going on here. Commented May 26, 2021 at 1:15
  • @WillWalsh i added the json file Commented May 26, 2021 at 1:26
  • I mean the server code at that URL that handles the receipt of the data from the ReactJS frontend. Is it a NodeJS/Express server handling :3002/posts? Possibly also try adding a console.log({name, email}); before the axios.post call to ensure that the data is being seen. Commented May 26, 2021 at 1:30
  • @WillWalsh this? POST /posts/ 201 33.528 ms - 42 Commented May 26, 2021 at 1:57
  • add console.log(name, email) when you trigger the handleSubmit Commented May 26, 2021 at 2:04

1 Answer 1

1

Your hooks are used in the wrong way, try to use it like this

  const handleChangeName = (event) => {
    setName(event.target.value);
  };

  const handleChangeEmail = (event) => {
    setEmail(event.target.value);
  };

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

Comments

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.