Home / React JS / How to fetch API Data from API in React Using useEffect?

How to fetch API Data from API in React Using useEffect?

import React, { useState, useEffect } from "react";
// Use can use css from this file:  import "./styles.css";
const url = "https://jsonplaceholder.typicode.com/posts";
function App() {
  const [userData, setUserData] = useState({});
  const getUserData = async () => {
    const response = await fetch(url);
    const jsonData = await response.json();
    setUserData(jsonData);
  };
  useEffect(() => {
    getUserData();
  }, []);
  console.log(userData);
  return (
    <div className="App">
      {Object.values(userData).map(function (currentElement) {
        return (
          <div>
            <p>{currentElement.userId}</p>
            <p>{currentElement.id}</p>
            <p>{currentElement.title}</p>
            <p>{currentElement.body}</p>
          </div>
        );
      })}
    </div>
  );
}
export default App;

About admin

Check Also

Import is not working in React. Showing SyntaxError unexpected token ‘<'

Solution:- Go to Jest-config.js and put this command that is transformIgnorePatterns: ["<rootDir>/node_modules/(?![a-z])"], Save and Run …

Leave a Reply

Your email address will not be published. Required fields are marked *