Last active
July 22, 2023 19:33
-
-
Save sdsanchezm/3539f4964a5f192e69cf8d77f1502220 to your computer and use it in GitHub Desktop.
GET request with headers in React using axios
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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