Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

221
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda