Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import axios from "axios";
- import { useState, useEffect } from "react";
- const MyComponent = () => {
- // State to store the fetched data
- const [data, setData] = useState([]);
- useEffect(() => {
- // Function to fetch data
- const fetchData = async () => {
- try {
- // Fetching data from JSONPlaceholder using Axios
- const response = await axios.get(
- "https://jsonplaceholder.typicode.com/posts"
- );
- // Update the state with the fetched data
- setData(response.data);
- } catch (error) {
- console.error("Error fetching data:", error);
- }
- };
- // Call the fetchData function
- fetchData();
- }, []); // Empty dependency array ensures this effect runs only once on mount
- return (
- <div>
- <h1>Data from JSONPlaceholder</h1>
- <ul>
- {/* Mapping over the data and rendering each item */}
- {data.map((item) => (
- <li key={item.id}>{item.title}</li>
- ))}
- </ul>
- </div>
- );
- };
- export default MyComponent;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement