A
A
AntonHPL2021-05-31 10:52:36
React
AntonHPL, 2021-05-31 10:52:36

How to display Loading... while loading?

https://codesandbox.io/s/eager-oskar-471xm?file=/s...
setLoading doesn't work.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
n1ksON, 2021-05-31
@AntonHPL

setLoading should only change to false when data has already been received.
And you didn’t set the key to the list with repositories, React swears

import React, { useState, useEffect } from "react";
import Search from "./components/Search";
import ReactPaginate from "react-paginate";
import axios from "axios";
import "./styles.css";
const PER_PAGE = 4;
const App = () => {
  const [user, setUser] = useState(null);
  const [currentPage, setCurrentPage] = useState(0);
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);

  async function getUser(login) {
    let result0;
    result0 = (await axios.get(`https://api.github.com/users/${login}`)).data;
    setUser(result0);
  }

  useEffect(() => {
    if (user) {
      setLoading(true);
      fetch(
        `//api.github.com/users/${user.login}/repos?page=${currentPage}&per_page=${PER_PAGE}`
      )
        .then((res) => res.json())
        .then(setData).then(() => setLoading(false));
    }
  }, [user, currentPage]);
  console.log(loading);
  function handlePageClick({ selected: selectedPage }) {
    setCurrentPage(selectedPage + 1);
  }

  /* const offset = currentPage * PER_PAGE;*/

  const currentPageData = data
    /* .slice(offset, offset + PER_PAGE)*/
    .map((post, i) => <p key={i}>{post.full_name}</p>);

  if (loading) {
    return <div class="loader">Loading...</div>;
  }

  if (user === null) {
    return (
      <div>
        <Search onSearch={getUser} />
        <div id="start">
          Start with searching
          <br />a GitHub user
        </div>
      </div>
    );
  } else if (user) {
    return (
      <div>
        <Search onSearch={getUser} />
        <ReactPaginate
          previousLabel={"← Previous"}
          nextLabel={"Next →"}
          pageCount={Math.ceil(user.public_repos / PER_PAGE)}
          onPageChange={handlePageClick}
          containerClassName={"paginatio"}
          previousLinkClassName={"paginatio__link"}
          nextLinkClassName={"paginatio__link"}
          disabledClassName={"paginatio__link--disabled"}
          activeClassName={"paginatio__link--active"}
        />
        <div id="cpd">{currentPageData}</div>
        <span id="repositories">Repositories({user.public_repos})</span>
      </div>
    );
  }
};

export default App;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question