Update state after axios POST request instead of page refresh

Viewed 1745

I have a form with input fields 'title' and 'body', they are being added to MongoDB after submitting the form, but the new post item shows up only after I refresh the page (that of course is not how it should work), but I want to know what I am doing wrong and how to fix the handleSumbit function?

Here is my code:

import { useState, useEffect } from "react";
import axios from "axios";
import "./App.css";

function App() {
    const [title, setTitle] = useState("");
    const [body, setBody] = useState("");
    const [posts, setPosts] = useState([]);

    const url = "http://localhost:8005/";

    useEffect(() => {
        const fetchPosts = async () => {
            const response = await axios(`${url}posts`);
            setPosts(response.data);
        };
        fetchPosts();
    }, []);

    const handleTitleChange = (event) => {
        setTitle(event.target.value);
    };

    const handleBodyChange = (event) => {
        setBody(event.target.value);
    };

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

        axios.post(`${url}posts`, { title: title, body: body })
          .then((res) => {
             console.log(res.data);
        });

        alert("Post added!");

        setTitle("");
        setBody("");
    };

    console.log(posts);

    return (
        <div className="App">
            {posts.map((post) => (
                <div className="post" key={post.id}>
                    <h4>{post.title}</h4>
                    <p>{post.body}</p>
                </div>
            ))}
            <form onSubmit={handleSubmit}>
                <label>
                    Mew post:
                    <input
                        type="text"
                        name="title"
                        placeholder="Add title"
                        onChange={handleTitleChange}
                    />
                    <input
                        type="text"
                        name="body"
                        placeholder="Add body"
                        onChange={handleBodyChange}
                    />
                </label>
                <button type="submit">Add</button>
            </form>
        </div>
    );
}

export default App;
1 Answers

The problem is that you didn't update the posts state after you sent the axios post request. Edit the below code block:

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

    axios.post(`${url}posts`, { title: title, body: body })
      .then((res) => {
         console.log(res.data);
         // save the new post to posts
         setPosts([...posts, res.data])
    });

    alert("Post added!");

    setTitle("");
    setBody("");
};
Related