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

113
Vistas
How do I wrap methods in react components

I have a lot of functions looking like this

  doSomething = async (...) => {
    try {
      this.setState({loading: true});

      ...
      var result = await Backend.post(...);
      ...

      this.setState({loading: false});
    } catch(err) {
      this.setState({error: err});
    }
  }

Basically I have 2 variables loading & error that I have to manage for a lot of functions and the code is basically the same for all of them. Since there are no decorators in javascript and I do not wish to install any experimental lib for that how could I wrap this function to remove the duplicated setStates from above ?

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Here is my current way, I pass the function as parameter.

We have many API, fetch data form backend, we have to handle error and do something with data.

Only data of service are different, the handling error is the same.

private processServiceResponse(resp: any, doSthWithData: (data: any) => void) {
    let { errors } = resp;
    if (this.hasError(errors)) {
      this.handleServiceErr(errors);
      return;
    }
    let data = resp;
    if (resp && resp.data) {
      data = resp.data;
    }
    doSthWithData(data);
  }

And here is how i pass function as parameter.

let rest1 = service1.getData();
processServiceResponse(rest1,(data)=>{
//only need to focus with processing data.
})

PS: It's typescript coding.

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can use a Higher Order Function (a function that takes as argument another function) to make the common loading and error functionality reusable. It is very similar to a decorator pattern. For example:

const doSomething = withLoadingAndErrorHandling(Backend.post, this.setState);


function withLoadingAndErrorHandling(fn, setState) {
    return async function(...args) {
       try {
          setState({loading: true});
          var result = await fn(args); 
          setState({loading: false});
          return result;
        } catch(err) {
          setState({error: err});
        }
    }

}
about 4 years ago · Juan Pablo Isaza Denunciar

0

if you are using function conponents, you can define a custom hook to avoid repeat code

//useFetch.js

import { useState, useEffect } from 'react';
import axios from 'axios';

function useFetch(url) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(null);
  const [error, setError] = useState(null);

  useEffect(() => {
      setLoading('loading...')
      setData(null);
      setError(null);
      const source = axios.CancelToken.source();
      axios.get(url, { cancelToken: source.token })
      .then(res => {
          setLoading(false);
          //checking for multiple responses for more flexibility 
          //with the url we send in.
          res.data.content && setData(res.data.content);
          res.content && setData(res.content);
      })
      .catch(err => {
          setLoading(false)
          setError('An error occurred. Awkward..')
  })
      return () => {
          source.cancel();
      }
  }, [url])

   return { data, loading, error }

export default useFetch;

usage:

import useFetch from './useFetch';
import './App.css';

function App() {
  const { data: quote, loading, error } = 
useFetch('https://api.quotable.io/random')

  return (
    <div className="App">
      { loading && <p>{loading}</p> }
      { quote && <p>"{quote}"</p> }
      { error && <p>{error}</p> }
    </div>
  );
}

export default App;
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