Fetching APIs
in React.js
can be done using various methods. One of the most common approaches is to use the built-in fetch API
or libraries like Axios
. Here's how you can fetch an API
in React.js
using both methods:
Using fetch API:
import React, { useState, useEffect } from 'react';
function App() {
const [data, setData] = useState(null);
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch('https://api.example.com/data');
const jsonData = await response.json();
setData(jsonData);
} catch (error) {
console.error('Error fetching data:', error);
}
};
fetchData();
}, []); // Empty dependency array means it will run only once on component mount
return (
<div>
{data ? (
<div>
{/* Render your fetched data here */}
</div>
) : (
<p>Loading...</p>
)}
</div>
);
}
export default App;
Using Axios:
First, install Axios using npm or yarn:
npm install axios
Then, you can use Axios in your React component:
import React, { useState, useEffect } from 'react';
import axios from 'axios';
function App() {
const [data, setData] = useState(null);
useEffect(() => {
const fetchData = async () => {
try {
const response = await axios.get('https://api.example.com/data');
setData(response.data);
} catch (error) {
console.error('Error fetching data:', error);
}
};
fetchData();
}, []); // Empty dependency array means it will run only once on component mount
return (
<div>
{data ? (
<div>
{/* Render your fetched data here */}
</div>
) : (
<p>Loading...</p>
)}
</div>
);
}
export default App;
Both methods achieve the same result. You fetch data from an API endpoint and update the component's state with the fetched data. The useEffect
hook is used with an empty dependency array to ensure that the API call is made only once when the component mounts.
Array methods in react.js
Fragment in react.js
Conditional rendering in react.js
Children component in react.js
use of Async/Await in react.js
Array methods in react.js
JSX in react.js
Event Handling in react.js
Arrow function in react.js
Virtual DOM in react.js
React map() in react.js
How to create dark mode in react.js
How to use of Props in react.js
Class component and Functional component
How to use of Router in react.js
All React hooks explain
CSS box model
How to make portfolio nav-bar in react.js
Top comments (0)