EN
React - fetch data using axios GET request with api key parameter (as variable)
1 answers
0 points
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:
xxxxxxxxxx
1
'https://api.nasa.gov/planetary/apod?api_key=my-api-key'
My code:
xxxxxxxxxx
1
import { useState, useEffect } from 'react';
2
import axios from 'axios';
3
4
const API_KEY = 'my-api-key'; // I want to pass it in GET request.
5
6
const MyComponent = () => {
7
const [data, setData] = useState();
8
9
useEffect(() => {
10
const fetchData = async () => {
11
try {
12
// Temporary solution with api_key=API_KEY hardcoded in URL:
13
const response = await axios.get('https://api.nasa.gov/planetary/apod?api_key=my-api-key');
14
setData(response.data);
15
} catch (e) {
16
console.error(e);
17
}
18
};
19
fetchData();
20
}, []);
21
22
return (
23
<div>
24
<div>{JSON.stringify(data)}</div>
25
</div>
26
);
27
};
28
29
export default MyComponent;
1 answer
0 points
You can pass an object as a second argument of axios GET request, which contains object with params
property:
xxxxxxxxxx
1
{
2
params: {
3
api_key: apiKey,
4
}
5
};
In your case it would be:
xxxxxxxxxx
1
import { useState, useEffect } from 'react';
2
import axios from 'axios';
3
4
const API_KEY = 'my-api-key';
5
6
const MyComponent = () => {
7
const [data, setData] = useState();
8
9
useEffect(() => {
10
const fetchData = async () => {
11
try {
12
const response = await axios.get('https://api.nasa.gov/planetary/apod', {
13
params: {
14
api_key: API_KEY
15
}
16
});
17
setData(response.data);
18
} catch (e) {
19
console.error(e);
20
}
21
};
22
fetchData();
23
}, []);
24
25
return (
26
<div>
27
<div>{JSON.stringify(data)}</div>
28
</div>
29
);
30
};
31
32
export default MyComponent;
See also
0 commentsShow commentsAdd comment