Home > Back-end >  React Native how to export API response
React Native how to export API response

Time:03-10

how to export API response to another components? i have axios that bring data from the back-end to the front-end, can i export the response data to another component/screen or i have to do Fetch/axios on each part i want render data on it

i have the API response on Home page, so i can export the data

Home.js

.....
const Home = ({ navigation }) => {
  const [ChartData, setChartData] = useState([]);
  const [BalanceData, setBalanceData] = useState([]);
  const [ExpensesData, setExpensesData] = useState([]);
  const [SavingsData, setSavingsData] = useState([]);
  const [IncomeData, setIncomeData] = useState([]);
  const [LoansData, setLoansData] = useState([]);


  const getData = () => {
    axios.get('http://192.168.8.143:8000/transactions/')
  .then(function (response) {
    // handle success
    console.log(response);
    setChartData(response.data);
    let data = response.data;
    let balance =  data?.filter((vl) => {
      return vl?.type == "BALANCE"
    });

    setBalanceData(balance)

    let savings =  data?.filter((vl) => {
      return vl?.type == "SAVING"
    })

    setSavingsData(savings);

    let loans =  data?.filter((vl) => {
      return vl?.type == "LOANS"
    });
    setLoansData(loans);

    let income =  data?.filter((vl) => {
      return vl?.type == "INCOME"
    });
    setIncomeData(income);

    let expenses =  data?.filter((vl) => {
      return vl?.type == "EXPENSES"
    })

    setExpensesData(expenses);

  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  
  }

  useEffect(() => {
    getData();
  }, [])



    console.log("Chart Data", ChartData);
...
...
export default Home;

CodePudding user response:

In this scenario it is usually a good idea to encapsulate your business logic in a custom hook which you can then reuse in every functional component. This could look as follows.

export const useMyBackendApi = () => {

  const [ChartData, setChartData] = useState([]);
  const [BalanceData, setBalanceData] = useState([]);
  const [ExpensesData, setExpensesData] = useState([]);
  const [SavingsData, setSavingsData] = useState([]);
  const [IncomeData, setIncomeData] = useState([]);
  const [LoansData, setLoansData] = useState([]);


  const getData = () => {
    axios.get('http://192.168.8.143:8000/transactions/')
  .then(function (response) {
    // handle success
    console.log(response);
    setChartData(response.data);
    let data = response.data;
    let balance =  data?.filter((vl) => {
      return vl?.type == "BALANCE"
    });

    setBalanceData(balance)

    let savings =  data?.filter((vl) => {
      return vl?.type == "SAVING"
    })

    setSavingsData(savings);

    let loans =  data?.filter((vl) => {
      return vl?.type == "LOANS"
    });
    setLoansData(loans);

    let income =  data?.filter((vl) => {
      return vl?.type == "INCOME"
    });
    setIncomeData(income);

    let expenses =  data?.filter((vl) => {
      return vl?.type == "EXPENSES"
    })

    setExpensesData(expenses);

  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  
  }

  useEffect(() => {
    getData();
  }, [])

  return {
    ChartData,
    BalanceData,
    ExpenseData,
    SavingsData,
    IncomeData,
    LoansData,
  }
}

The in your Screen, you can use your hook.

const Home = ({ navigation }) => {
    const { ChartData, BalanceData } = useMyBackendApi() // destructure whatever you need from your hook

    ...

    // do whatever
}

You can do the same in any other functional component.

It might be a good idea to cache your server response in order to prevent unwanted refetches. This could be done using SWR Hooks. This could be used as follows in your scenario.

import useSWR from 'swr'

export const useMyBackendApi = () => {

  // first param is your cache key, second param your fetcher
  const { data, error, mutate } = useSWR("http://192.168.8.143:8000/transactions/", (url) => {
    return axios.get('http://192.168.8.143:8000/transactions/')
  .then(function (response) {
   
    let data = response.data;
    let balance =  data?.filter((vl) => {
      return vl?.type == "BALANCE"
    });

    let savings =  data?.filter((vl) => {
      return vl?.type == "SAVING"
    })

    let loans =  data?.filter((vl) => {
      return vl?.type == "LOANS"
    });
    
    let income =  data?.filter((vl) => {
      return vl?.type == "INCOME"
    });
    
    let expenses =  data?.filter((vl) => {
      return vl?.type == "EXPENSES"
    })
    
    return {
        chartData: response.data,
        balanceData: balance,
        savingsData: savings,
        loansData: loans,
        incomeData: income,
        expensesData: expenses 
    } 
  })
    
 })

 const refresh = React.useCallback(() => {
     return mutate()
 }, [mutate])

  return {
    data,
    refresh,
    error
  }
}

Your data is now cached using swr hooks and your buisness logic is encapsulated in a custom hook. You can reuse this in every screen as follows.

const Home = ({ navigation }) => {

   const {data} = useMyBackendApi()

   console.log(data.incomeData)
}

The procedure is the same in any other screen. Notice, that your data will not be refetched unless you trigger a mutate of your cache using the mutate function of swr. However, you could make the use of dependent cache keys for more complex situations.

  • Related