Top 10 Solutions for Utilizing Coinmarketcap API

Jennie Lee
8 min readApr 2, 2024

--

Looking for a Postman alternative?

Try APIDog, the Most Customizable Postman Alternative, where you can connect to thousands of APIs right now!

Introduction to building a real-time cryptocurrency info table with React, MUI, and CoinMarketCap API

Building a real-time cryptocurrency info table can be a great way to stay updated with the latest prices and changes in the crypto market. With the help of React, a popular JavaScript library for building user interfaces, and MUI (Material-UI), a React UI framework, we can create a dynamic and interactive table that displays information such as the name, price, 24-hour percentage change, market cap, and volume of various cryptocurrencies. To fetch the data, we will be utilizing the CoinMarketCap API, which provides real-time data on more than 5,000 cryptocurrencies.

In this tutorial, we will walk through the process of setting up a project and building a real-time cryptocurrency info table using React, MUI, and the CoinMarketCap API. We will start by setting up the project, installing the necessary dependencies, and obtaining an API key from CoinMarketCap. Then, we will move on to building the backend using Express and Axios to fetch data from the CoinMarketCap API. Finally, we will build the frontend using create-react-app and MUI, and implement features such as pagination, data fetching, loading state, and formatting.

By the end of this tutorial, you will have a fully functional cryptocurrency info table that fetches real-time data from the CoinMarketCap API and displays it in an organized and visually appealing manner. So let’s get started!

Setting up the project

Before we begin building our cryptocurrency info table, we need to set up the project by creating a new folder and installing the necessary dependencies for both the frontend and the backend.

  1. Create a new folder for your project using a command-line interface of your choice:
mkdir cryptocurrency-info-table
  1. Navigate into the project folder:
cd cryptocurrency-info-table
  1. Install the necessary dependencies for the frontend and backend. For the frontend, we will be using create-react-app to bootstrap our React app:
npx create-react-app frontend
  1. Next, navigate into the frontend directory:
cd frontend
  1. Start the frontend development server:
npm start
  1. Open your browser and navigate to http://localhost:3000. You should see a default React app running.

Now that the frontend is set up, let’s move on to setting up the backend.

  1. Open a new terminal window and navigate to the root directory of your project:
cd ..
  1. Create a new folder for the backend and navigate into it:
mkdir backend
cd backend
  1. Initialize a new Node.js project:
npm init -y
  1. Install the necessary dependencies:
npm install express axios

Now that the project is set up, let’s initialize the frontend and backend with some initial configurations.

Building the backend

In order to fetch data from the CoinMarketCap API, we need to set up a backend server using Express. This server will act as an intermediary between our frontend app and the CoinMarketCap API.

  1. Create a new file named server.js in the backend directory:
touch server.js
  1. Open server.js in your preferred code editor and import the necessary modules:
const express = require('express');
const axios = require('axios');
  1. Create an instance of the Express server:
const app = express();
const port = 5000;
  1. Set up a route for fetching data from the CoinMarketCap API. We will use the /api/data route for this purpose:
app.get('/api/data', (req, res) => {
const apiKey = 'YOUR_API_KEY';
const apiUrl = `https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?CMC_PRO_API_KEY=${apiKey}`;

axios
.get(apiUrl)
.then((response) => {
res.json(response.data);
})
.catch((error) => {
console.error(error);
res.status(500).json({ error: 'Failed to fetch data from CoinMarketCap API' });
});
});

Make sure to replace 'YOUR_API_KEY' with your actual CoinMarketCap API key.

  1. Start the server and listen on the specified port:
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});

With the backend set up and running, we can now move on to building the frontend.

Building the frontend

In this section, we will build the frontend of our cryptocurrency info table using React and MUI (Material-UI). We will create a table component using MUI’s Table component and add features such as pagination and data fetching.

  1. Open the frontend directory in your preferred code editor.
  2. Replace the contents of src/App.js with the following code:
import React from 'react';
import CoinTable from './components/CoinTable';

function App() {
return (
<div className="App">
<h1>Cryptocurrency Info Table</h1>
<CoinTable />
</div>
);
}

export default App;

This code sets up the basic structure of the app and imports the CoinTable component, which we will create next.

  1. Create a new directory named components inside the src directory.
  2. Inside the src/components directory, create a new file named CoinTable.js and add the following code:
import React from 'react';
import { Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Paper, TablePagination } from '@mui/material';
import useCoinMarket from '../hooks/useCoinMarket';

const CoinTable = () => {
const { loading, data, page, rowsPerPage, handleChangePage, handleChangeRowsPerPage } = useCoinMarket();

if (loading) {
return <>Loading...</>;
}

// ...
};

export default CoinTable;

This code imports the necessary components from MUI and the useCoinMarket custom hook that we will create later. It also initializes the loading, data, page, and rowsPerPage variables using the useCoinMarket hook, and displays a simple loading message while the data is being fetched.

  1. Add the following code inside the CoinTable component, right before the export default CoinTable line:
const CoinTable = () => {
// ...

return (
<>
<TableContainer component={Paper}>
<Table>
<TableHead>
<TableRow>
<TableCell>Name</TableCell>
<TableCell>Price</TableCell>
<TableCell>24h % Change</TableCell>
<TableCell>Market Cap</TableCell>
<TableCell>Volume</TableCell>
</TableRow>
</TableHead>
<TableBody>
{/* Render table rows */}
</TableBody>
</Table>
</TableContainer>
{/* Render pagination */}
</>
);
};

This code sets up the basic structure of the table component, including the table headers for each column. We will fill in the table rows and pagination functionality later.

  1. Install the required dependencies for MUI:
npm install @mui/material @emotion/react@^11.0.0 @emotion/styled@^11.0.0
  1. Open src/index.js and replace its contents with the following code:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';

import { createTheme, ThemeProvider } from '@mui/material/styles';

const theme = createTheme();

ReactDOM.render(
<ThemeProvider theme={theme}>
<App />
</ThemeProvider>,
document.getElementById('root')
);

This code sets up the MUI theme and wraps the App component with the ThemeProvider. It also imports the index.css file, which we will create next.

  1. Create a new file named index.css in the src directory and add the following code:
body {
margin: 0;
padding: 0;
}

.App {
text-align: center;
margin-top: 2rem;
}

.MuiToolbar-regular {
justify-content: center;
}

.MuiTableContainer-root {
margin-top: 2rem;
}

This code applies some basic styling to the app and centers the toolbar and table container.

With the frontend set up, we can now move on to fetching data and managing the loading state.

Fetching data and managing loading state

In this section, we will create a custom hook called useCoinMarket to handle fetching data from the CoinMarketCap API and managing the loading state. We will also create the CoinTableBody component to render the table rows and implement pagination functionality.

  1. Inside the src/components directory, create a new file named useCoinMarket.js and add the following code:
import { useEffect, useState } from 'react';
import axios from 'axios';

const useCoinMarket = () => {
const [loading, setLoading] = useState(true);
const [data, setData] = useState([]);
const [page, setPage] = useState(0);
const [rowsPerPage, setRowsPerPage] = useState(10);

useEffect(() => {
const fetchData = async () => {
try {
const response = await axios.get('/api/data');
setData(response.data);
setLoading(false);
} catch (error) {
console.error(error);
}
};

fetchData();
}, []);

const handleChangePage = (_, newPage) => {
setPage(newPage);
};

const handleChangeRowsPerPage = (event) => {
setRowsPerPage(parseInt(event.target.value, 10));
setPage(0);
};

const slicedData = data.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage);

return { loading, data: slicedData, page, rowsPerPage, handleChangePage, handleChangeRowsPerPage };
};

export default useCoinMarket;

This code sets up the useCoinMarket custom hook, which fetches data from the CoinMarketCap API using the /api/data route we set up earlier. It manages the loading state, pagination, and provides the sliced data based on the current page and number of rows per page.

  1. Import the CoinTableBody component and the necessary components from MUI in the CoinTable.js file:
import { TableBody, TableCell, TablePagination, TableRow } from '@mui/material';
import CoinTableBody from './CoinTableBody';
  1. Replace the commented out section inside the CoinTable component's return statement with the following code:
<TableBody>
<CoinTableBody
data={data}
page={page}
rowsPerPage={rowsPerPage}
handleChangePage={handleChangePage}
handleChangeRowsPerPage={handleChangeRowsPerPage}
/>
</TableBody>
<TablePagination
component="div"
count={data.length}
page={page}
onPageChange={handleChangePage}
rowsPerPage={rowsPerPage}
onRowsPerPageChange={handleChangeRowsPerPage}
/>

This code renders the CoinTableBody component, passing in the necessary props for data, page, rowsPerPage, and the handleChangePage and handleChangeRowsPerPage functions. It also renders the TablePagination component for pagination functionality.

  1. Create a new file named CoinTableBody.js inside the src/components directory and add the following code:
import React from 'react';
import { TableCell, TableRow, SwitchTransition, Fade } from '@mui/material';
import { formatNumber, formatPercentage } from '../utils/format';

const CoinTableBody = ({ data, page, rowsPerPage }) => {
const rowData = data.map((coin) => ({
id: coin.id,
name: coin.name,
price: coin.price,
percentChange24h: coin.percentChange24h,
marketCap: coin.marketCap,
volume: coin.volume,
}));

return (
<SwitchTransition>
<Fade key={`${page}-${rowsPerPage}`}>
<>
{rowData.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage).map((coin) => (
<TableRow key={coin.id}>
<TableCell>{coin.name}</TableCell>
<TableCell>{formatNumber(coin.price)}</TableCell>
<TableCell>{formatPercentage(coin.percentChange24h)}</TableCell>
<TableCell>{formatNumber(coin.marketCap)}</TableCell>
<TableCell>{formatNumber(coin.volume)}</TableCell>
</TableRow>
))}
</>
</Fade>
</SwitchTransition>
);
};

export default CoinTableBody;

This code formats the data received from the API and renders each row of the table using the TableRow and TableCell components from MUI. It also adds a fade-in transition effect using the SwitchTransition and Fade components.

  1. Create a new directory named utils inside the src directory.
  2. Inside the src/utils directory, create a new file named format.js and add the following code:
export const formatNumber = (number) => {
const formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
});

return formatter.format(number);
};

export const formatPercentage = (percentage) => {
const formatter = new Intl.NumberFormat('en-US', {
style: 'percent',
minimumFractionDigits: 2,
maximumFractionDigits: 2,
});

return formatter.format(percentage / 100);
};

This code exports two utility functions, formatNumber and formatPercentage, which format numbers and percentages using the Intl.NumberFormat object.

  1. Start the development server for both the frontend and backend:
cd frontend
npm start
cd backend
node server.js

Open your browser and navigate to http://localhost:3000 to see your cryptocurrency info table in action!

The loading state

One of the key aspects of building a good user experience is to handle the loading state properly. In this section, we will add a loading indicator to the frontend while the data is being fetched from the backend.

  1. Inside the CoinTable.js file, replace the Loading... text with the following code:
import CircularProgress from '@mui/material/CircularProgress';

// ...

if (loading) {
return (
<div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
<CircularProgress />
</div>
);
}

// ...

This code imports the CircularProgress component from MUI and renders it in the center of the screen while the data is being fetched.

  1. Restart the frontend development server and refresh your browser to see the loading indicator in action.

Congratulations! You have successfully built a real-time cryptocurrency info table using React, MUI, and the CoinMarketCap API. You can further customize the table by adding additional columns or implementing sorting functionality. This project serves as a great starting point for creating your own cryptocurrency dashboard or monitoring tool. Happy coding!

Looking for a Postman alternative?

Try APIDog, the Most Customizable Postman Alternative, where you can connect to thousands of APIs right now!

--

--

Jennie Lee
Jennie Lee

Written by Jennie Lee

Software Testing Blogger, #API Testing

No responses yet