Custom Hooks not returning data

Hi! I have a custom Hook to fetch data from two differents Api.
The first call returns some currencies codes that i stored in currenciesCodes array.
Second calls returns currencies codes and their respective name, then stored in currenciesNames.
Then i filtered the last filterd to match codes from previous array, and then set currencies with the filtered array.

Problem is that currencies is still an empty array, but i can’t figure out why.

import { useState, useEffect } from 'react';

import ExchangeRates from '../api/ExchangeRates';
import OpenExchangeRates from '../api/OpenExchangeRates';

const useGetCurrencies = () => {
  const [currenciesCodes, setCurrenciesCodes] = useState([]);
  const [currenciesNames, setCurrenciesNames] = useState([]);
  const [currencies, setCurrencies] = useState([]);

  useEffect(() => {
    fetchExchangeRates();
    fetchCurrenciesDetails();
    filterCurrencies(currenciesCodes, currenciesNames);
  }, []);

  const fetchExchangeRates = async () => {
    const response = await ExchangeRates.get('');
    const currencies = ['EUR'];
    const rates = [{code: 'EUR', rate: 1}]
    for (const [key] of Object.entries(response.data.rates)) {
      currencies.push(key);
    }
    setCurrenciesCodes(currencies);
  };

  const fetchCurrenciesDetails = async () => {
    const response = await OpenExchangeRates.get('currencies.json');
    const currenciesNames = [];
    for (const [key, value] of Object.entries(response.data)) {
      currenciesNames.push({key, value});
    }
    setCurrenciesNames(currenciesNames);
  };

  const filterCurrencies = (currenciesCodes, currenciesNames) => {
    if(currenciesCodes.length && currenciesNames.length) {
      const currenciesList = currenciesNames.filter(currenciesName => currenciesCodes.includes(currenciesName.key));
      setCurrencies(currenciesList);
    }
  }

  return [currencies, fetchExchangeRates];
}

export default useGetCurrencies;

Because first two functions are async and by the time the third function runs there is no data yet.

changin third function to this:

const filterCurrencies = async (currenciesCodes, currenciesNames) => {
    if(currenciesCodes.length && currenciesNames.length) {
      const currenciesList = await currenciesNames.filter(currenciesName => currenciesCodes.includes(currenciesName.key));
      setCurrencies(currenciesList);
    }
  }

didn’t help at all

That’s not what I meant.
All three functions are run one by one, but because there is data fetching, the results don’t arrive fast enough to be available for filtering.

You should do something like this:

Promise.all([fetchExchangeRates(), fetchCurrenciesDetails()])
.then(([currenciesCodes, currenciesNames]) => {
  filterCurrencies(currenciesCodes, currenciesNames) {
    ...
  }
})
1 Like