Languages

React - fetch data using axios GET request with api key parameter (as variable)

0 points
Asked by:
Majid-Hajibaba
972

How can I fetch data from API using axios GET request with api key from a variable?

I want to fetch data from NASA API using unique api_key generated on their website, but I'm not sure how to pass it as apiKey variable inside GET request.

Right now I am passing it inside url like this and it works:

'https://api.nasa.gov/planetary/apod?api_key=my-api-key'

My code:

import { useState, useEffect } from 'react';
import axios from 'axios';

const API_KEY = 'my-api-key'; // I want to pass it in GET request.

const MyComponent = () => {
    const [data, setData] = useState();

    useEffect(() => {
        const fetchData = async () => {
            try {
                // Temporary solution with api_key=API_KEY hardcoded in URL:
                const response = await axios.get('https://api.nasa.gov/planetary/apod?api_key=my-api-key');
                setData(response.data);
            } catch (e) {
                console.error(e);
            }
        };
        fetchData();
    }, []);

    return (
        <div>
          <div>{JSON.stringify(data)}</div>
        </div>
    );
};

export default MyComponent;
1 answer
0 points
Answered by:
Majid-Hajibaba
972

You can pass an object as a second argument of axios GET request, which contains object with params property:

{
    params: {
        api_key: apiKey,
    }
};

In your case it would be:

import { useState, useEffect } from 'react';
import axios from 'axios';

const API_KEY = 'my-api-key';

const MyComponent = () => {
    const [data, setData] = useState();

    useEffect(() => {
        const fetchData = async () => {
            try {
                const response = await axios.get('https://api.nasa.gov/planetary/apod', {
                    params: {
                        api_key: API_KEY
                    }
                });
                setData(response.data);
            } catch (e) {
                console.error(e);
            }
        };
        fetchData();
    }, []);

    return (
        <div>
          <div>{JSON.stringify(data)}</div>
        </div>
    );
};

export default MyComponent;

 

See also

0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join