-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:
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:
from here to
page
???const r = await api('/usuarios');
– novic
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.
– Matheus Paice