Advertisement
alaniarati

L8 - Source

Dec 3rd, 2023
834
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 1.05 KB | Source Code | 0 0
  1. import axios from "axios";
  2. import { useState, useEffect } from "react";
  3.  
  4. const MyComponent = () => {
  5.   // State to store the fetched data
  6.   const [data, setData] = useState([]);
  7.  
  8.   useEffect(() => {
  9.     // Function to fetch data
  10.     const fetchData = async () => {
  11.       try {
  12.         // Fetching data from JSONPlaceholder using Axios
  13.         const response = await axios.get(
  14.           "https://jsonplaceholder.typicode.com/posts"
  15.         );
  16.         // Update the state with the fetched data
  17.         setData(response.data);
  18.       } catch (error) {
  19.         console.error("Error fetching data:", error);
  20.       }
  21.     };
  22.  
  23.     // Call the fetchData function
  24.     fetchData();
  25.   }, []); // Empty dependency array ensures this effect runs only once on mount
  26.  
  27.   return (
  28.     <div>
  29.       <h1>Data from JSONPlaceholder</h1>
  30.       <ul>
  31.         {/* Mapping over the data and rendering each item */}
  32.         {data.map((item) => (
  33.           <li key={item.id}>{item.title}</li>
  34.         ))}
  35.       </ul>
  36.     </div>
  37.   );
  38. };
  39.  
  40. export default MyComponent;
  41.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement