Home > OS >  Do I need to use await for async actions in react components?
Do I need to use await for async actions in react components?

Time:12-31

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?

CodePudding user response:

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

CodePudding user response:

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

  • Related