Page with Reactjs consuming from an API

Asked

Viewed 888 times

-2

Yesterday I was having a problem in being able to create a page with nodejs for my API and with help from the community got me a north and I managed to solve that situation.

What’s the idea? There is a Mysql database with 37 user records and I want to list them on my web page.

What’s the matter?. I happen to be consuming my API in React and it is only bringing me the first 10 records and if I pass my example url: users? page=2 or users? page=3, it does not help, as it continues to bring only the first 10 records.

Image bringing only the first 10 records:

inserir a descrição da imagem aqui

My API:

import axios from 'axios';

const api = Xios.create({ baseURL:'http://localhost:3010', })

export default api;

Consuming the API

  componentDidMount(){
  this.call();     
}

async call(){
    const r = await api('/usuarios');
//    console.log(r.data);
    this.setState({
        usuarios:r.data
    }) 
}

Rendering in React

render(){
    const { usuarios } = this.state;
    return(
    <div>
        {usuarios.map((items,index)=>{
            return(
                <li key={index}>
                    <p>id:{items.id}</p>
                    <p>Email:{items.email}</p>
                </li>
            )
        })}
    </div>
    );
}

Query of the Bank

if(results){
        const rows = results.length; // Existe 37 registros no banco
        let { page = 1 } = req.query; // passando argumento pela url >> usuarios?page=1
        let calc = Math.ceil(rows/10); // calc recebe a quantidade de páginas existentes

        if(page == ''){
            page = 1;
        }

            let count = (page*10)-10;

        const qtd = connection.query(`SELECT * FROM usuarios_homos LIMIT 10 OFFSET ${count}`,(err,result,fields)=>{
                if(err){
                    console.log(err);
                }else{
                    res.send(result);
                }

            });
    }

Route in the Nodejs

router.get('/usuarios',queryController);

Tests performed in India work well:

inserir a descrição da imagem aqui

  • 1

    from here to page ??? const r = await api('/usuarios');

  • Watch out!! In the API, every query that comes from req is string type, so don’t forget to convert this parameter to number before performing paging operations.

1 answer

0


The problem is that you are not passing which page to endpoint:

async call(page = 1){
    const r = await api('/usuarios', { params: { page  });
    this.setState({ usuarios: r.data }) ;
}

note that you have to pass the correct page number when calling the function call

if you want to take the page number of the query string you can take the value of the property location.search that will return something like ?page=2, then you can manipulate this string to get the parameter

  • hmn. I was able to once again advance my pagination application, I used>> Let params = window.location.search; const r = await api('/users'+ params ); .... That would be right?!

Browser other questions tagged

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