Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to achieve useEffect like hook in angular?

Tags:

angular

hook

how can i use useEffect like hook in angular?

in react we do this:

 useEffect(() => {
    const fetchUser = async () => {
      const res = await axios.get(`/users?id=${post?.userId}`);
      setUser(res.data);
    };
    fetchUser();
}, [post?.userId]);

as we can see this hook will only run when user-id changes, now i want to achieve this same functionality in angular.

in my current code(angular):

ngOnInit(): void {
    const res = this.postService.getAllPosts();
    this.postService.setPosts(res);
}

i want ngOnInit to run again only when user-id changes.

like image 942
Deep Vasoya Avatar asked Oct 22 '25 20:10

Deep Vasoya


1 Answers

ngOnInit will run only once in your application, after the ngOnChanges lifecycle hook.

I'm not sure if I understood your question, you want to 'listen' to a class property change and trigger a method?

If you want to accomplish this, you can use a set method to a class property to trigger a method every time it receives a new value. Something like:

  export class AppComponent {
      set foo(userId: string) {
        // Do something here
      }
  }

You could also use ngDoCheck lifecycle hook, this will be triggered every time a data change in your component happens, although invoking this method multiple times can make your application slower.

like image 88
RenanSchwyz Avatar answered Oct 24 '25 10:10

RenanSchwyz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!