Skip to content

Instantly share code, notes, and snippets.

@sdsanchezm
Last active July 22, 2023 19:33
Show Gist options
  • Save sdsanchezm/3539f4964a5f192e69cf8d77f1502220 to your computer and use it in GitHub Desktop.
Save sdsanchezm/3539f4964a5f192e69cf8d77f1502220 to your computer and use it in GitHub Desktop.
GET request with headers in React using axios
import React, { useEffect, useState } from 'react';
function ComponentExample() {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
const axiosInstance = axios.create({
baseURL: 'https://example.com/api',
headers: {
'Authorization': 'Bearer TOKEN_HERE',
'Content-Type': 'application/json',
},
});
useEffect(() => {
const fetchData = async () => {
try {
const response = await axiosInstance.get('/endpointpath');
setData(response.data);
setLoading(false);
} catch (error) {
console.error('An error ocurred when fetching data:', error);
setLoading(false);
}
};
fetchData();
}, []);
if (loading) {
return <div>Loading...</div>;
}
return (
<div>
{data.map(item => (
<div key={item.id}>{item.name}</div>
))}
</div>
);
};
export default ComponentExample;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment