React-JS -useState, useEffect

Asked

Viewed 128 times

-1

Good afternoon guys, I have code where I am using a class for the status of my application. It is a simple application only at the level of study. In the application I am calling an external api where I show your data on the screen and created 02 buttons (Previous and Next). Now I want to convert that state to function using useState and useEffect. Can anyone help me convert it?

import React, { Component } from 'react';
import Api from '../../services/api.jsx'
import './style.css'

export default class Main extends Component{
    state ={
        products: [],
        productInfo: {},
        page: 1,
    }

    componentDidMount() {
    this.loadProducts()
}

loadProducts = async (page = 1) => {
    const res = await Api.get(`/products?page=${page}`) // Buscando api externa

    const { docs,  ...productInfo} = res.data
    this.setState({products: docs, productInfo, page}) // Armazenando as variaveis 
}

// Função para retornar uma página
prevPage = () => {
    const {page, productInfo} = this.state
    if (page === 1) return

    const pageNumber = page - 1
    this.loadProducts(pageNumber)
}

// Função para ir a proxima pagina
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(prod => (
               
                   <article key={prod._id}>
                       <strong>{prod.title}</strong>
                       <p>{prod.description}</p>
        
                        <a href="">Acessar</a>
                   </article>
                ))}
                <div className="actions">
                    <button onClick={this.prevPage}>Anterior</button>
                    <button onClick={this.nextPage}>Próximo</button>
                </div>
            </div>
    )}
}

1 answer

0

Basically with React Hooks:

import React, { useState, useEffect } from 'react';
import Api from '../../services/api.jsx'
import './style.css'

function Main() {
    const [products, setProducts] = useState([]);
    const [productInfo, setProductInfo] = useState({});
    const [page, setPage] = useState(1);        
    useEffect(()=>{
        loadProducts();
    }, []);
    async function loadProducts(page = 1) {
        const res = await Api.get(`/products?page=${page}`)
        const { docs,  ...productInfo} = res.data
        setProducts(docs);
        setProductInfo(productInfo);
        setPage(page);
    }
    function prevPage() {        
        if (page === 1) {
            return;
        }
        const pageNumber = page - 1
        loadProducts(pageNumber)
    }
    function nextPage(){        
        if(page === productInfo.pages) {
            return;
        }
        const pageNumber = page + 1
        loadProducts(pageNumber)      
    }
    return (        
        <div className="product-list">
            {products.map(prod => (           
               <article key={prod._id}>
                   <strong>{prod.title}</strong>
                   <p>{prod.description}</p>    
                    <a href="">Acessar</a>
               </article>
            ))}
            <div className="actions">
                <button onClick={prevPage}>Anterior</button>
                <button onClick={nextPage}>Próximo</button>
            </div>
        </div>
    )
}
export default Main;
  • Thank you so much for the answer, gave to have a good understanding!!! It is returning the following error: Unhandled Rejection (Typeerror): setProductInfo is not a Function

  • In which line at which time @Senaoliveira something else try to study because it’s a silly mistake, you need to understand ... go for me

  • True! I’ll be trying to settle here, thank you very much!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.