Overview
TheuseCryptoData 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
Return Value
The hook returns an object with the following properties:Array of cryptocurrency objects fetched from the CoinLore API. Each object contains:
id: Unique identifier for the cryptocurrencyname: Full name of the cryptocurrencyrank: Market ranksymbol: Trading symbol (e.g., BTC, ETH)price_usd: Current price in USDpercent_change_24h: 24-hour price change percentage
Indicates whether the data is currently being fetched.
true during the initial fetch, false once complete.Contains an error message if the API request fails, otherwise
null.How It Works
The hook performs the following operations:- Fetches Data: Makes a GET request to
https://api.coinlore.net/api/tickers/ - Maps Response: Converts the raw API response into
Cryptomodel instances - State Management: Manages three states:
data: Stores the cryptocurrency arrayloading: Tracks the fetch statuserror: Captures any fetch errors
- Runs Once: Uses
useEffectwith an empty dependency array to fetch data only on component mount
Usage Example
Here’s how the hook is used in theHomeScreen component:
API Source
The hook fetches data from the CoinLore API:- Endpoint:
https://api.coinlore.net/api/tickers/ - Method: GET
- Response Format: JSON with a
dataarray 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:- Logs the error to the console:
Error al obtener criptomonedas - Sets the
errorstate to"Error al obtener criptomonedas" - Sets
loadingtofalse