Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

112
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!