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

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

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

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

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 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