Home > front end >  Render page when database contents changes
Render page when database contents changes

Time:03-09

So suppose I have a page that displays all the user's posts. Right now when the user creates a post, it stores it into the database. But that new post will not appear unless I log out of the app and log back in. How can I make it so that the post will appear without having to logout?

const [Posts,setPosts] = useState([])

useEffect(()=>{
const fetchUserPosts = async () => {
const res = await client.get('/fetch-user-posts')
setPosts(res.data.posts)
}
fetchUserPosts()
},[])

And in the rendering I just took the Posts and map it to display its contents. I know this problem exists somewhere but I don't know what keywords to google. I have seen posts asking to use JQuery but I bet there is a simpler solution? Any pointers are appreciated.

CodePudding user response:

Take the function of fetchUserPosts out of the useEffect like this:

    const fetchUserPosts = async () => {
        const res = await client.get('/fetch-user-posts')
        setPosts(res.data.posts)
    }

Now, useEffect will be like this:

    useEffect(() => {
        fetchUserPosts()
    }, [])

Next, wherever you function of create user posts is, call fetchUserPosts() like this:

    const addUserPosts = async () => {
        // logic of adding new user post
        if (success) {
            await fetchUserPosts()
        }
    }
  • Related