Skip to main content

Overview

The useCryptoData hook is a custom React hook that fetches cryptocurrency data from the CoinLore API and manages the loading, error, and data states. It automatically fetches data when the component mounts and returns the cryptocurrency list along with loading and error states.

Signature

useCryptoData(): {
  data: CryptoApiResponse[];
  loading: boolean;
  error: string | null;
}

Return Value

The hook returns an object with the following properties:
data
CryptoApiResponse[]
Array of cryptocurrency objects fetched from the CoinLore API. Each object contains:
  • id: Unique identifier for the cryptocurrency
  • name: Full name of the cryptocurrency
  • rank: Market rank
  • symbol: Trading symbol (e.g., BTC, ETH)
  • price_usd: Current price in USD
  • percent_change_24h: 24-hour price change percentage
loading
boolean
Indicates whether the data is currently being fetched. true during the initial fetch, false once complete.
error
string | null
Contains an error message if the API request fails, otherwise null.

How It Works

The hook performs the following operations:
  1. Fetches Data: Makes a GET request to https://api.coinlore.net/api/tickers/
  2. Maps Response: Converts the raw API response into Crypto model instances
  3. State Management: Manages three states:
    • data: Stores the cryptocurrency array
    • loading: Tracks the fetch status
    • error: Captures any fetch errors
  4. Runs Once: Uses useEffect with an empty dependency array to fetch data only on component mount

Usage Example

Here’s how the hook is used in the HomeScreen component:
import { useCryptoData } from '../hooks/useCryptoData';
import { useFilter } from '../context/FilterContext';

const HomeScreen = () => {
  // Fetch cryptocurrency data
  const { data, loading, error } = useCryptoData();
  
  // Get current filter from context
  const { filter } = useFilter();

  // Filter cryptocurrencies based on user input
  const filtered = data.filter((crypto) => {
    const nameMatch = crypto.name.toLowerCase().includes(filter.text.toLowerCase());
    const symbolMatch = crypto.symbol.toLowerCase().includes(filter.text.toLowerCase());

    const minOk = filter.minPrice === null || Number(crypto.price_usd) >= filter.minPrice;
    const maxOk = filter.maxPrice === null || Number(crypto.price_usd) <= filter.maxPrice;

    return (nameMatch || symbolMatch) && minOk && maxOk;
  });

  return (
    <View>
      {loading && <ActivityIndicator size="large" color="#0000ff" />}
      {error && <Text>{error}</Text>}
      
      <ScrollView>
        {filtered.map((crypto) => (
          <CryptoCard key={crypto.id} crypto={crypto} />
        ))}
      </ScrollView>
    </View>
  );
};

API Source

The hook fetches data from the CoinLore API:
  • Endpoint: https://api.coinlore.net/api/tickers/
  • Method: GET
  • Response Format: JSON with a data array containing cryptocurrency information
The hook only fetches data once when the component mounts. If you need to refresh the data, you’ll need to implement a manual refresh mechanism or remount the component.

Error Handling

If the API request fails, the hook:
  1. Logs the error to the console: Error al obtener criptomonedas
  2. Sets the error state to "Error al obtener criptomonedas"
  3. Sets loading to false
You should handle the error state in your component by displaying an appropriate message to users.

Build docs developers (and LLMs) love