Home > database >  Array.map not reconginizing the array and not printing data
Array.map not reconginizing the array and not printing data

Time:09-05

I have a simple function component, where I am making a .get() call and then later in my jsx I am just mapping through using .map() an array to print data.

But for some reason, the array is not recognizable and it is not printing the data.

useEffect() is working fine. It is logging out data. But, the books array is just not working and I'm unable to figure out why

below is the code.

 const [books, setBooks] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState();

  useEffect(() => {
    setLoading(true);
    axios
      .get("database.json")
      .then((response) => {
        const request = response.data.results.books;
        console.log("request", request);
        setBooks(books);
      })
      .catch(function (error) {
        // handle error
        console.log(error);
      })
      .finally(() => {
        setLoading(false);
      });
  }, []);

  if (loading) {
    return <p>Data is loading...</p>;
  }

  if (error || !Array.isArray(books)) {
    return <p>There was an error loading your data!</p>;
  }

  return (
    <div className="row">
      <h2>LOREN IPSUM</h2>
      <div className="row__posters">
        {books.map((book) => (
          <img
            // onClick={() => handleClick(book)}
            key={book.title}
            className="row__poster row__posterLarge"
            src={book.book_image}
            alt={book.title}
          />
        ))}
      </div>
      {/* {description && <span /> />} */}
    </div>
  

); }

CodePudding user response:

setBooks(books);

You are updating the books with their current value.

=> Change this to setBooks(request);

  • Related