React: Fetching and Displaying Data and Handling Error

index.js

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";

ReactDOM.render(
  <App login="<username>" />,
  document.getElementById("root")
);

App.js

import React, { useState, useEffect } from "react";
import "./App.css";


// https://github.com/users/<username>

function App ({ login }){
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  useEffect(() => {
    if (!login) return;
    setLoading(true);
    fetch(`https://api.github.com/users/${login}`)
      .then(response => response.json())
      .then(setData)
      .then(() => setLoading(false))
      .catch(setError);
  }, [login]);

  if (loading) return <h2>Loading.....</h2>;
  if (error) 
      return 
      <pre>
        {JSON.stringify(error, null, 2)}
      </pre>;

  if (!data) return null;

    return (
    <div>
      <h1>{data.name}</h1>
      <p>{data.location}</p>

    </div>
    );
  }

export default App;

Result:

image.png

No Comments Yet