How to Handle html response from api or axios
Vimal
Posted on March 21, 2024
import React, { useEffect, useState } from 'react';
function App() {
const [data, setData] = useState([]);
useEffect(() => {
// Function to fetch data from the API
const fetchData = async () => {
try {
// Make the API call
const response = await fetch('https://example.com/api/endpoint');
// Check if the request was successful
if (response.ok) {
// Parse the HTML content
const htmlText = await response.text();
const parser = new DOMParser();
const doc = parser.parseFromString(htmlText, 'text/html');
// Find the HTML elements containing the data you want to extract
const dataElements = doc.querySelectorAll('.data-element');
// Extract the data from the HTML elements
const extractedData = Array.from(dataElements).map(element => element.textContent.trim());
// Set the extracted data in the state
setData(extractedData);
} else {
console.error('Failed to fetch data from the API:', response.status);
}
} catch (error) {
console.error('Error fetching data:', error);
}
};
// Call the fetchData function when the component mounts
fetchData();
}, []); // Empty dependency array ensures this effect runs only once on mount
return (
Extracted Data
-
{data.map((item, index) => (
- {item} ))}
);
}
export default App;
💖 💪 🙅 🚩
Vimal
Posted on March 21, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
watercooler Why does a reboot make your PC run SO much faster than running all the cleaning tools you can possibly imagine?
November 30, 2024