skip to Main Content

I want to call useEffect() whenever a state change occurs in my index.js file.

index.js

export default withAuth(function Home() {

    const [post, setPost] = useState([])

    const getPosts = async () => {
        const data = await instance.get('/post')
        setPost(data.data)
    }
    useEffect(() => {
        getPosts()
    }, [])
    return (
        <>
            <Navbar currentPage="home" user={getUser()} />
            <div className={styles.home}>
                <div className={styles.content}>
                    {
                        post.map((item, index) => {
                            return (
                                <PostCard key={index} {...item} />
                            )
                        })
                    }
                </div>
            </div>
        </>
    )
}
)

When the state post changes, useEffect() method should be called.
If I enter post as a dependency for useEffect(), it will be called infinitely.

My requirement is when a user creates new post, useEffect should run and fetch posts from the database

2

Answers


  1. You can add another state and toggle it each time you update post state:

    const [trigger, setTrigger] = useState(true)
    

    Now each time you update post you do also

    setTrigger(prev => !prev) // but not from useEffect
    

    and finally you include trigger instead of post in the useEffect dependecies


    a better approach is to fetch data directly from your function handler each time you need to and don’t use useEffect for that, makes more sense

    Login or Signup to reply.
  2. Actually, you don’t need useEffect to rerun in this case. I believe there should be a handler somewhere handling the creation of a new post. You call call getPosts in that handler when a new post is created. That would be a much better approach in my opinion.

    In a scenario where you don’t have control of the new post creation process, then you might want to depend on polling to fetch posts at intervals or listen to a web socket event for when a new post is created.

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