Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

220
Views
Do I need to use await for async actions in react components?

I made this store:

export class CommentStore {
  comments = []

  constructor() {
    makeAutoObservable(this, {}, { autoBind: true });
  }

  async loadPostComments(postId: number): Promise<void> {
    const res = await API.loadPostComments(postId);
    runInAction(() => {
      this.comments = res;
    });
  }

  async sendComment(postId: number, comment: Comment): Promise<void> {
    try {
      await API.sendComment(postId, comment);
      await this.loadPostComments(postId);
      return true;
    } catch (err) {
      console.log('oops');
    }
  }
}

Do i need use await in react components? For example:

useEffect(() => {
      (async function () {
        await loadPostComments(postId);
      })();
    }, [loadPostComments, postId]);

But this also works fine:

useEffect(() => {
  loadPostComments(postId);
}, [loadPostComments, postId]);

Same for sendComment onClick:

onClick={()=>{sendComment(postId, comment)}}
onClick={async ()=>{await sendComment(postId, comment)}}

So, is it necessary to use await in this situations?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You want to await something only if it is necessary, e.g. when the next line of code uses the data from Promise. In the useEffect case that you provided it is not necessary and on onClick handlers as well

about 4 years ago · Juan Pablo Isaza Report

0

Yes it is unnecessary to write async/await on them. you just have to write the async call on the functions and that is enough.

for example:

 const [posts, setPosts] = useState([]);

 useEffect(() => {
    const loadPost = async () => {

        // Await make wait until that 
        // promise settles and return its result
        const response = await axios.get(
        "https://jsonplaceholder.typicode.com/posts/");

        // After fetching data stored it in some state.
        setPosts(response.data);
    }

    // Call the function
    loadPost();
}, []);

` there is no need to write promise and async / await on everything, remember ;P

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!