skip to Main Content
import {useState} from 'react';
import axios from "axios";

export default function CreateiPhone(){
    const [iphone, setiPhone] = useState({
        id: "",
        name: "",
        model: "",
        configuration: "",
        imgUrl: "",
    });
    const handleChange = (e) => {
        const value = e.target.value;
        setiPhone({...iphone, [e.target.name]: value });
    };
    const handleSubmit = async (e) => {
        e.preventDefualt();

        axios.post("http://localhost:8080/api/createiPhone", {iphone})
        .then((response) => {
            console.log(response.status, response.data);
        })
        .catch((error) => {
            console.error('Error:', error);
        });
    };

Below is the form that should send that data on submit to my endpoint.

        <div>
            <form onSubmit={(e) => handleSubmit(e)}>
                <label htmlFor="Id">ID:</label>
                <input
                    id="Id"
                    type = "text"
                    name = "id"
                    value={iphone.id}
                    onChange={(e) => handleChange(e)}
                />
                <label htmlFor="Name">
                    Name:
                </label>
                <input
                    id="Name"
                    type = "text"
                    name = "name"
                    value={iphone.name}
                    onChange={(e) => handleChange(e)}
                />
                <label htmlFor="Model">
                    Model:
                </label>
                <input
                    id="Model"
                    type="text"
                    name="model"
                    value={iphone.model}
                    onChange={(e) => handleChange(e)}
                />
                <label htmlFor="Configuration">
                    Configuration:
                </label>
                <input
                    id="Configuration"
                    type="text"
                    name="configuration"
                    value={iphone.configuration}
                    onChange={(e) => handleChange(e)}
                />
                <label htmlFor="ImgUrl">
                    imgUrl:
                </label>
                <input
                    id="ImgUrl"
                    type="text"
                    name="imgUrl"
                    value={iphone.imgUrl}
                    onChange={(e) => handleChange(e)}
                />
                <button
                type="submit">
                    Submit
                </button>
            </form>
        </div>

Below is the server-side code

    @PostMapping("/api/createiPhone")
    public iPhoneItem create(@RequestBody iPhoneItem iphoneitem) {
        return iphoneservice.createiPhone(iphoneitem);
    }

Here is the iPhoneItem class

package com.iPhoneRepair.iPhoneRepairApp.model;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document
public class iPhoneItem {

    @Id
    private String id;

    private String name;
    private String model;
    private String configuration;
    private String imgUrl;

    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getModel() {
        return model;
    }

    public String getConfiguration() {
        return configuration;
    }

    public void setId(String id) {
        this.id = id;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setModel(String model) {
        this.model = model;
    }

    public void setConfiguration(String configuration) {
        this.configuration = configuration;
    }

    public String getImgUrl() {
        return imgUrl;
    }

    public void setImgUrl(String imgUrl) {
        this.imgUrl = imgUrl;
    }

}

I know I can send data to my database through the Spring Boot endpoint I created, however I can’t seem to send my form data to that endpoint or at least it does not show up in my database. When I submit the form the page refreshes and nothing is outputted to the console.

2

Answers


  1. Given your controller method binds the request body to your iPhoneItem class…

    @RequestBody iPhoneItem iphoneitem
    

    and your model looks like this

    public class iPhoneItem { // 👈 FYI this is not a good Java class name
      private String id;
      private Stringb name;
      // ...
    

    When you post data like this

    axios.post("http://localhost:8080/api/createiPhone", {iphone})
    

    {iphone} is the same as { iphone: iphone } (see Object initializer – Property definitions) so you’re actually sending a request body like this where everything is nested under an "iphone" property

    {
      "iphone": {
        "id": "...",
        "name": "...",
        ...
      }
    }
    

    which doesn’t match your @RequestBody model.

    const iphone = {
      id: "1",
      name: "iPhone 15",
      model: "iPhone 15",
      configuration: "all space taken by OS",
      imgUrl: "https://example.com/iphone15.jpg",
    };
    
    console.log("compare");
    console.log(iphone);
    console.log({iphone});
    .as-console-wrapper { max-height: 100% !important; }

    Simply remove the {...} to send the data without nesting

    //                                                   👇 no braces
    axios.post("http://localhost:8080/api/createiPhone", iphone)
    

    I highly recommend you adopt Typescript in your client-side code. Then you would easily catch typos like e.preventDefualt()

    const handleSubmit: FormEventHandler<HTMLSelectElement> = async (e) => {
      e.preventDefault(); // 👈 no chance of a typo now
      // ...
    
    Login or Signup to reply.
  2. Change e.preventDefualt() to e.preventDefault(). What is happening is the default submit behavior is to refresh the page. Since it is not being called correctly, the default behavior is happening and the page is refreshing without your POST request being fired.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search