score:0

you don't need newarr.

const[books, setbooks] = usestate([]);

is already specifying books in it. use it to map over the items.

also, if get books is an asynchronous call. you can do a ternary to render null when the array is empty. this will prevent the initial loop with empty values in your markup and providing more checks on something like book.name which results in name of undefined errors.

like this


 books ? books.map(book => {}) : null;

score:0

you need to return your element after mapping your array otherwise it will not render.

import react, { useeffect, usestate } from 'react';

import "./app.css";

function app() {
  const[books, setbooks] = usestate([]);

  useeffect(() => {
    fetch(`https://api.nytimes.com/svc/books/v3/lists/best-sellers/history.json?api-key=${your_api_key}`,{
      method: "get"
    })
    .then(res=>res.json())
    .then(res=>setbooks(res.results))
    .catch(err=>console.log(err));
  },[]);

  return (
   <div classname="content_books">
      {books.map((item, index) => <div
       key={index}
       classname="card">
        <img src="https://s1.nyt.com/du/books/images/9780553897845.jpg" classname="card-img-top" alt="game of thrones" />
        <div classname="card-body">
           <h5 classname="card-title">{item.title}</h5>
           <p classname="card-text">{item.description}</p>
           <a href="#" classname="btn btn-primary">buy</a>
         </div>
        </div>
      )}

   </div>
  );
}

export default app;

score:0

you must know how lambda functions works. if you are using {} you have to use return, because this is block of code:

new arr.map(item => {
    return (
        <div>{item}<div>
    );
}

but lambda functions without {} by default use return statement:

new arr.map(item => (
        <div>{item}<div>
    );

Related Query

More Query from same tag