Home > Net >  Data created with form onSubmit is not saved correctly (React Hooks and JSON)
Data created with form onSubmit is not saved correctly (React Hooks and JSON)

Time:02-20

I have a form that it needs to create the item "post" with a unique id, title, author and content. Something like this:

{
  "posts": [
    {
      "id": 1,
      "title": "First post",
      "author": "Mathew",
      "content": "This is a content"
    },
    {
      "id": 2,
      "title": "Second post",
      "author": "Oliver",
      "content": "This is a content 2"

The problem is that when I submit a new post, it is saved in the json server like this:

{
  "posts": [
    {
      "posts": {
        "title": "First post",
        "author": "Mathew",
        "content": "This is content"
      },
      "id": 5
    },
    {
      "posts": {
        "title": "Second post",
        "author": "Oliver",
        "content": "This is content"
      },
      "id": 6
    }
  ]
}

"id" is outside the element created, and "posts" are outsite from the parent "posts". This is my code:

form:

const New: React.FC = () => {
    // const [newPost, setNewPost] = useState("");
    const [newPost, setNewPost] = useState({
        title: '',
        author: '',
        content: ''
    })

    const handleInputChange = (e: React.FormEvent<HTMLInputElement>) => {
        console.log((e.target as HTMLInputElement).value)
        setNewPost({
            ...newPost,
            [(e.target as HTMLInputElement).name]: (e.target as HTMLInputElement).value
        })
    };

    const createPost = (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault(); //Detiene el formulario para que no actualize la página
        setPost(newPost)
    }

    return (
        <div className="containerHomepage">
            <form className="formulari" onSubmit={createPost}>
                <div className="containerBreadCrumb">
                    <ul className="breadCrumb">
                        <li>Posts</li>
                    </ul>
                </div>

                <div className="containerTitleButton">
                    <input
                        className=""
                        type="text"
                        placeholder='Post title'
                        name="title"
                        onChange={handleInputChange}
                    ></input>
                    <button
                        className="button"
                        type="submit"
                    >Save</button>
                </div>

                <div className="containerEdit">
                    <input
                        className=""
                        type="text"
                        placeholder='Author'
                        name="author"
                        onChange={handleInputChange}
                    ></input>
                    <input
                        className=""
                        type="text"
                        placeholder='Content'
                        name="content"
                        onChange={handleInputChange}
                    ></input>
                </div>

            </form>
        </div>
    );
};


// ========================================

export default New;

And here the function setPost, to create a new post:

export function setPost(posts) {
    return fetch('http://localhost:3004/posts', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ posts })
    })
      .then(data => data.json())
   }

I imagine it must be some small error in the code, but I can't figure out what is the problem.

CodePudding user response:

You are creating an object again when converting it into a JSON string.

export function setPost(posts) {
    return fetch('http://localhost:3004/posts', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(posts) // Correction
    })
      .then(data => data.json())
}
  • Related