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
You can add another state and toggle it each time you update
post
state:Now each time you update
post
you do alsoand finally you include
trigger
instead ofpost
in theuseEffect
dependeciesa 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 senseActually, 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 callgetPosts
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.