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(() => {
    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( {

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

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

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

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

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.