Last active
March 23, 2019 13:31
-
-
Save raulpesilva/84f7932c69d8b974c2fd057657629793 to your computer and use it in GitHub Desktop.
code rocketseat
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component } from "react"; | |
import api from "../../services/api"; | |
import "./style.css"; | |
export default class Main extends Component { | |
state = { | |
products: [], | |
productInfo: {}, | |
page: 1 | |
}; | |
componentDidMount() { | |
this.loadProducts(); | |
} | |
loadProducts = async (page = 1) => { | |
const response = await api.get(`/products?page=${page}`); | |
console.log(response.data.docs); | |
const { docs, ...productInfo } = response.data; | |
this.setState({ products: response.data.docs, productInfo, page }); | |
}; | |
prevPage = () => { | |
const { page, productInfo } = this.state; | |
if (page === 1) return; | |
const pageNumber = page - 1; | |
this.loadProducts(pageNumber); | |
}; | |
nextPage = () => { | |
const { page, productInfo } = this.state; | |
if (page === productInfo.pages) return; | |
const pageNumber = page + 1; | |
this.loadProducts(pageNumber); | |
}; | |
render() { | |
const { products } = this.state; | |
return ( | |
<div className="product-list"> | |
{products.map(product => ( | |
<article key={product._id}> | |
<strong>{product.title}</strong> | |
<p>{product.description}</p> | |
<a href="">Acessar</a> | |
</article> | |
))} | |
<div className="actions"> | |
<button disabled={page === 1} onClick={this.prevPage}> | |
Anterior | |
</button> | |
<button disabled={page === productInfo.page} onClick={this.nextPage}> | |
Proximo | |
</button> | |
</div> | |
</div> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment