I write in case someone has already gone through the same thing, it turned out that I am using react paginate to create a pagination here the documentation
Take the example and adapt it to my case. The problem is that when it loads for the first time it does not load the information, I know that pagination works well because it only works when I make changes to the code and save (ctrl+s)
I assume that the error may be in the time it takes for the api to respond because when, however, I have already tried using promises and many other solutions.
So in summary to make it clearer:
I consume an endpoint that gives me an array of information that I save in the const
Avisos
using the state hook, with the seconduseEffect()
what is done is to divide the arrayAvisos
with the hooksetCurrentItems()
,currentItems
finally they are the items that are shown on the first page.
In the image above is the console when the page first loads
The image above is when I make changes to the code and save those changes (ctrl+s)
I've been having this problem for a while, I've tried using just one useEffect
, I've changed the dependencies of the useEffect
, I've tried using promises, async await.
`iimport React, { useState,useEffect } from 'react'
import {getUrlApi, peticionAxios,getUrlImages} from "../../Funciones.js"
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faComments, faEye, faHandshake, faMagnifyingGlass, faEraser} from '@fortawesome/free-solid-svg-icons'
import {Link} from "react-router-dom"
import Accordion from 'react-bootstrap/Accordion';
import ReactPaginate from 'react-paginate';
import Swal from 'sweetalert2'
import withReactContent from 'sweetalert2-react-content'
import RegionesComponent from '../Regiones'
export default function ListadoAvisos(props, { itemsPerPage=6 }){
const MySwal = withReactContent(Swal)
let ruta = getUrlImages(),json = null
const iconComments = <FontAwesomeIcon icon={faComments} color="orange" size="lg"/>
const iconViews = <FontAwesomeIcon icon={faEye} color="blue" />
const iconHands = <FontAwesomeIcon icon={faHandshake} color="green"/>
const iconBuscar = <FontAwesomeIcon icon={faMagnifyingGlass} />
const iconBorrar = <FontAwesomeIcon icon={faEraser} />
let method = "GET"
const token = localStorage.getItem("token")
const idUsuario = localStorage.getItem("id")
const [Avisos,setAvisos] = useState([])
const [estados,setEstados] = useState([])
const [categorias,setCategorias] = useState([])
//Empezamos con una lista vacia
const [currentItems, setCurrentItems] = useState(null);
const [pageCount, setPageCount] = useState(0);
const [itemOffset, setItemOffset] = useState(0);
const [filtroTitulo,setFiltroTitulo] = useState("")
const [filtroComuna,setFiltroComuna] = useState(0)
const [filtroEstado,setFiltroEstado] = useState(0)
const [filtroCategorias,setFiltroCategorias] = useState(0)
useEffect(() => {
cargarComboEstados()
cargarComboCategorias()
buscarAvisos()
},[])
//useState de paginacion
useEffect(() => {
console.log("Avisosssss",Avisos)
const endOffset = itemOffset + itemsPerPage;
setCurrentItems(Avisos.slice(itemOffset, endOffset));
setPageCount(Math.ceil(Avisos.length / itemsPerPage));
}, [itemOffset, itemsPerPage]);
//funcion para cuando cambian de pagina
const handlePageClick = (event) => {
const newOffset = (event.selected * itemsPerPage) % Avisos.length;
console.log(
`Se solicito la pagina ${event.selected}, which is offset ${newOffset}`
);
setItemOffset(newOffset);
};
const buscarAvisos = async()=>{
let url = getUrlApi()
let urlAvisos
(!props.MisAvisos)? urlAvisos= url+"avisos" : urlAvisos = url+`avisos/idUser/${idUsuario}`
if(props.MisAvisos){
json = {
idUsuario:idUsuario
}
}
await peticionAxios(urlAvisos,method,token,json).then(
res=>{
setAvisos(res.data.Avisos)
}
).catch((err)=>{
console.log(err)
}
)
}
const buscarAvisosFiltrado = ()=>{
setFiltroTitulo(document.getElementById("txtTituloFiltro").value)
setFiltroEstado(document.getElementById("sltFiltroEstado").value)
setFiltroCategorias(document.getElementById("sltFiltroCategoria").value)
setFiltroComuna(document.getElementById("sltComuna").value)
buscarAvisos()
}
const cargarComboEstados = ()=>{
let urlObtenerEstados = `${getUrlApi()}obtenerEstados`
peticionAxios(urlObtenerEstados,'GET',token).then(res=>{
if(res.status == 200){
setEstados(res.data)
}
}).catch(err=>{
console.error("Ha ocurrido un errro al cargar los estados")
console.log(err)
})
}
const cargarComboCategorias = ()=>{
let urlcategorias = `${getUrlApi()}categorias`
peticionAxios(urlcategorias,method,token, "").then(resultado=>{
if(resultado.status ==200){
setCategorias(resultado.data)
}else{
console.log("Ha ocurrido un error", resultado)
}
}).catch(err=>{
console.log(err)
})
}
const dibujarEstado = (estados)=>{
let estadoActual = estados.find(x=>x.pivot.activo===1)
if(estadoActual!==undefined){
let color = ""
switch(estadoActual.descripcionEstado){
case "Abierta":
color =`success`
break
case "Cerrada":
color =`danger`
break
case "Desierta":
color = `secondary`
break
case "Eliminada":
color = `dark`
break
default:
color = `danger`
break
}
return <span className={`btn btn-${color} btn-sm`}>{estadoActual.descripcionEstado}</span>
}
}
function Items({ currentItems }) {
console.info(currentItems)
return (
<>
{currentItems &&
currentItems.map((item) => (
<div key={item.id} className='col-md-4 p-3'>
<div>
<div className="card">
<div className='card-header'>
<div className='row'>
<div className="col-md-8">
<b>Subido por: </b>{item.name}
</div>
<div className="col-md-4">
{dibujarEstado(item.estados)}
</div>
</div>
</div>
<div className="card-body">
<div className='row'>
<div className='col-md-12'>
{item.imagen!==null?
<img className="card-img-top imageAviso" src={ruta + item.imagen} alt="Card image cap"/>
:""
}
</div>
<div className='col-md-12'>
<h4 className="card-title">{item.titulo}</h4>
</div>
<div className='col-md-12'>
<span><b>Ubicacion:</b>{item.nombreCiudad}, {item.nombreComuna}</span>
</div>
<p className="card-text">{item.descripcion}</p>
<div className='col-md-4'>
{iconComments} : {item.valoraciones.length}
</div>
<div className='col-md-4'>
{iconViews} : {item.vistas??0}
</div>
<div className='col-md-4'>
{iconHands} : {item.users.length??0}
</div>
<Link to={`../Aviso/idAviso=${item.id}`} className="btn btn-primary">Más informacion</Link>
{/* {botonPostular(item.idUsuario,item.id,item.titulo)} */}
</div>
</div>
<div className="card-footer">
<div className='row'>
<div className='col-md-12'>
<span><b>Fecha publicacion:</b> {item.fecha}</span>
</div>
</div>
</div>
</div>
</div>
</div>
))}
</>
);
}
if(Avisos.length>0){
return(
<div className='row m-2'>
<div className="col-md-12 col-sm-12 p-2">
<Accordion defaultActiveKey="0">
<Accordion.Item eventKey="0">
<Accordion.Header><h5 className="text-center">Filtrar busqueda</h5></Accordion.Header>
<Accordion.Body>
<div className="row">
<div className="col-md-3 col-sm-6">
<label className='w-100'>Buscar por titulo
<input type="text"
id="txtTituloFiltro"
className='form-control'
maxLength={30}
placeholder="Busque coincidencias en titulo"></input>
</label>
</div>
<div className="col-md-3 col-sm-6">
<RegionesComponent/>
</div>
<div className="col-md-3 col-sm-6">
<label>Estado</label>
<select id="sltFiltroEstado" className="form-control">
<option value="0">Seleccione</option>
{
estados.length>0?
estados.map(a=>{
return (<option value={a.id} key={a.id}>{a.descripcionEstado}</option>)
})
:""
}
</select>
</div>
<div className="col-md-3 col-sm-6">
<label>Categoria</label>
<select id="sltFiltroCategoria" className="form-control">
<option value="0">Seleccione</option>
{
categorias!==undefined?
categorias.map(a=>{
return (<option value={a.id} key={a.id}>{a.descripcionCategoria}</option>)
})
:""
}
</select>
</div>
<div className="col-md-3">
<button className="btn btn-outline-success m-1" onClick={()=>{buscarAvisosFiltrado()}}>{iconBuscar}Buscar</button>
<button className="btn btn-outline-dark m-1">{iconBorrar}Limpiar filtros</button>
</div>
</div>
</Accordion.Body>
</Accordion.Item>
</Accordion>
</div>
<div className='col-md-12 mt-2'>
<div className='row'>
<>
<Items currentItems={currentItems} />
<ReactPaginate
nextLabel="Siguiente >"
onPageChange={handlePageClick}
pageRangeDisplayed={3}
marginPagesDisplayed={2}
pageCount={pageCount}
previousLabel="< Anterior"
pageClassName="page-item"
pageLinkClassName="page-link"
previousClassName="page-item"
previousLinkClassName="page-link"
nextClassName="page-item"
nextLinkClassName="page-link"
breakLabel="..."
breakClassName="page-item"
breakLinkClassName="page-link"
containerClassName="pagination"
activeClassName="active"
renderOnZeroPageCount={null}
/>
</>
</div>
</div>
</div>
)
}else{
return (<><p>Sin avisos por ahora</p></>)
}
}`
The code above is the code of my component that has the error.