Fetch data Using Axios and Reactjs API
Here i would like to fetch data from a public API called FakeRestAPI.Web to get books and its iD
by Amir Danish
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js"></script>
<div id="app"></div>
CSS
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
}
li {
margin: 8px 0;
}
h2 {
font-weight: bold;
margin-bottom: 15px;
}
.done {
color: rgba(0, 0, 0, 0.3);
text-decoration: line-through;
}
input {
margin-right: 5px;
}
React
function App (){
const getBooks = () =>{
axios
.get('https://fakerestapi.azurewebsites.net/api/books')
.then((books) => setBooks(books.data))
.catch((error) => console.log(error));
};
const [books, setBooks] = React.useState([]);
console.log(books)
return (
<div>
<h1>Books List</h1>
<hr/>
<button onClick = {()=> getBooks()}>Get Books</button>
{books.map((book) => (
<div class="books" kye={book.ID}>
<h3>Title: {book.Title}</h3>
<img src={book.Url} />
</div>
))}
</div>
)
}
ReactDOM.render(<App />, document.querySelector("#app"))