React / Axios: fetch API data with key for CoinMarketCap

Viewed 3093

no experience in programming here... I've been reading some questions regarding this but couldn't manage to get it right. I use React for a small app and would like to fetch data from an API, Coinmarketcap in this case, but it requires a key, and don't know how to pass it through axios. Made a test request using Postman and it works ok.

This is how the API should receive the request (Node.js example):

const rp = require('request-promise');
const requestOptions = {
  method: 'GET',
  uri: 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest',
  qs: {
    'start': '1',
    'limit': '5000',
    'convert': 'USD'
  },
  headers: {
    'X-CMC_PRO_API_KEY': 'b54bcf4d-1bca-4e8e-9a24-22ff2c3d462c'
  },
  json: true,
  gzip: true
};

rp(requestOptions).then(response => {
  console.log('API call response:', response);
}).catch((err) => {
  console.log('API call error:', err.message);
});

And this is my React file's code:

import React, { Component } from 'react'
import axios from 'axios'

class Prices extends Component {

    state = {
        cryptos: []
    }

    componenDidMount() {

        axios.get('https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest', {
            headers: { 'X-CMC_PRO_API_KEY': 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee' }
        })
        .then(res => {
            console.log(res)
            this.setState({
                cryptos: res.data.slice(0,50)
            })
        });
    }
    render() {
        return(
            <div>asdf</div>
        )
    }
}

export default Prices

Obviously, I'm hiding my key up there.

  1. App is running ok
  2. No apparent errors, but also...
  3. No log in console

The question is not if I'm doing something wrong, but what...

I would like to thank you in advance for helping me.

Edit: Parent file code

import Layout from '../components/Layout'
import Prices from '../components/prices'
import axios from 'axios'

const Index = (props) => (
    <Layout>
        <div className="container">
            <h1>Welcome to CoinInfo</h1>
            <p>Check current Bitcoin rates</p>
            <Prices />
        </div>
    </Layout>
)

export default Index
2 Answers

You are missing the query string parameter in your request and also there is a typo. It's componentDidMount, the t is missing in the component.

Please try the below code.

import React, { Component } from 'react'
import axios from 'axios'
class Prices extends Component {
    state = {
        cryptos: []
    }

    componentDidMount() {
       this.fetchData();
    }

    async fetchData() {
        let qs = `?start=1&limit=5000&convert=USD`
        try {
            let res = await axios.get('https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest' + qs, {
                headers: { 'X-CMC_PRO_API_KEY': 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee' }
            });
            console.log(res)
            this.setState({
                cryptos: res.data.slice(0, 50)
            });
        } catch (error) {
            console.log(error);
        }

    }
    render() {
        return (
            <div>asdf</div>
        )
    }
}
export default Prices

According to the docs of CoinMarketCap

Making HTTP requests on the client side with Javascript is currently prohibited through CORS configuration. This is to protect your API Key which should not be visible to users of your application so your API Key is not stolen. Secure your API Key by routing calls through your own backend service.

What it means is that, they do not want you to make direct API calls from the browser or client. Instead they tell you to call a backend service which maps your user-id with the key and makes an intermediate call to the coinMarketCap website

For example, you can expose an API in node server which you call from client and in that API call the node server will call the coinMarketBase API and return you the result

Related