Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

222
Visualizações
How to fix pagination first page load all data but onclick rest button load correctly in react

First part of my code:

const Inventory = () => {
  const [products, setProducts] = useState([]);
  const [pageCount,setPageCount] = useState(0);
  //console.log(pageCount);
  const [page,setPage] = useState(0);
  const navigate = useNavigate();



  useEffect(() => {
    fetch(`http://localhost:3000/products?page=${page}`)
      .then((res) => res.json())
      .then((data) => setProducts(data));
  }, [products,page]);

  useEffect(()=>{
    axios.get('http://localhost:3000/product-count')
   .then((res) => {
      const productCount = res?.data?.count;
     //console.log("count product",count);
     const pages = Math.ceil(productCount/6);
     setPageCount(pages);
   })
     
 },[page])

Return section, this code will return pagination:

 <div className="pagination">
                {
                    [...Array(pageCount).keys()]
                    .map(number => <button key={number} className={page===number? 'selected': 'pagination'}
                      onClick={()=> setPage(number)}
                    >
                      {number+1}
                    </button>)
                  }
                  
         </div>

And this is the server-side code:

app.get("/products",async(req,res)=>{
        const page = parseInt(req.query.page);
        //console.log(page);
        const q = {};
        const cursor = productCollection.find(q);
        
        let result;
            if(page){
                 result = await cursor.skip(page * 6).limit(6).toArray();
            }
            else{
                result = await cursor.toArray();
            }
            res.send(result);
    })
// get product count
    app.get("/product-count",async(req,res)=>{
        const query = {};
        const count = await productCollection.countDocuments(query);
        res.json({count});
    })

I want to load 6 data on the first load. But when data loads it displays all data. When I click the pagination button it works fine except the 1st button.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

During the first load your front-end is sending page=0 to your backend.

In your server-side code you've the following statement: if (page)
But page will always be false when page=0, because 0 is a falsy value in javascript. So your statement always return the else block.

You need to change the statement to: if (page !== undefined)

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda