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:
'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
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