Sunday, May 30, 2021

React (function) Fetch Data From An API With React Hooks | AJAX and APIs

 


import React, { useState, useEffect } from "react";

const Planets = () => {
  const [hasError, setErrors= useState(false);
  const [planets, setPlanets= useState({});

  useEffect(() => {
    async function fetchData() {
      const res = await fetch("https://jsonplaceholder.typicode.com/posts");
      res
        .json()
        .then(res => setPlanets(res))
        .catch(err => setErrors(err));
    }

    fetchData();
  });

  return (
    <>
     {JSON.stringify(planets)}
      <hr/>
      <span>Has error: {JSON.stringify(hasError)}</span>
    </>
  )
}
export default Planets;

No comments:

Post a Comment

Fetching JSON data from REST APIs

data.json---------------------------------- [     {     "userId" : 1 ,     "id" : 1 ,     "title" : "sunt...