Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

222
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda