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

100
Visualizações
Search function now working in React photo gallary

Working on a small application that takes a pexels api and displays photos dynamically. When I send the search request for my api to fectch based on the new params, it does actually update the page with new photos but not the ones based on the params. I though I got the search function correct, maybe it's cause I'm not using it in a useEffect? But if I did use it in a useEffect, I wouldn't be able to set it on the onClick handle. I tried to console.log the query I was getting from the onChange but it doesn't seem like it's getting the result. What am I doing wrong?

import { useState, useEffect } from 'react'
import pexelsApi from './components/pexelsApi'
import './App.css'


const App = () => {
  const [images, setImages] = useState([]);
  const [loading, setLoading] = useState(false);
  const [nextPage, setNextPage] = useState(1);
  const [perPage, setPerPage] = useState(25);
  const [query, setQuery] = useState('');
  const [error, setError] = useState('');

  useEffect(() => {
    const getImages = async () => {
      setLoading(true);
      await pexelsApi.get(`/v1/curated?page=${nextPage}&per_page=${perPage}`)
        .then(res => {
          setImages([...images, ...res.data.photos]);
          setLoading(false);
        }).catch(er => {
          if (er.response) {
            const error = er.response.status === 404 ? 'Page not found' : 'Something wrong has happened';
            setError(error);
            setLoading(false);
            console.log(error);
          }
        });
    }
    getImages();
  }, [nextPage, perPage]);

  const handleLoadMoreClick = () => setNextPage(nextPage + 1)

  const search = async (query) => {
    setLoading(true);
    await pexelsApi.get(`/v1/search?query=${query}&per_page=${perPage}`)
      .then(res => {
        setImages([...res.data.photos]);
        console.log(res.data)
        setLoading(false);
        console.log(query)
      })
  }




  if (!images) {
    return <div>Loading</div>
  }

  return (
    <>
      <div>
          <input type='text' onChange={(event) => setQuery(event.target.value)} />
          <button onClick={search}>Search</button>
      </div>
      <div className='image-grid'>
        {images.map((image) => <img key={image.id} src={image.src.original} alt={image.alt} />)}
      </div>
      <div className='load'>
        {nextPage && <button onClick={handleLoadMoreClick}>Load More Photos</button>}
      </div>
    </>
  )
};

export default App

import axios from 'axios';

export default axios.create({
    baseURL: `https://api.pexels.com`,
    headers: {
        Authorization: process.env.REACT_APP_API_KEY
    }
});
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Your main issue is that you've set query as an argument to your search function but never pass anything. You can just remove the arg to have it use the query state instead but you'll then need to handle pagination...

// Helper functions
const getCuratedImages = () =>
  pexelsApi.get("/v1/curated", {
    params: {
      page: nextPage,
      per_page: perPage
    }
  }).then(r => r.data.photos)

const getSearchImages = (page = nextPage) =>
  pexelsApi.get("/v1/search", {
    params: {
      query,
      page,
      per_page: perPage
    }
  }).then(r => r.data.photos)

// initial render effect
useEffect(() => {
  setLoading(true)
  getCuratedImages().then(photos => {
    setImages(photos)
    setLoading(false)
  })
}, [])

// search onClick handler
const search = async () => {
  setNextPage(1)
  setLoading(true)
  setImages(await getSearchImages(1)) // directly load page 1
  setLoading(false)
}

// handle pagination parameter changes
useEffect(() => {
  // only action for subsequent pages
  if (nextPage > 1) {
    setLoading(true)

    const promise = query
      ? getSearchImages()
      : getCuratedImages()

    promise.then(photos => {
      setImages([...images, ...photos])
      setLoading(false)
    })
  }
}, [ nextPage ])

The reason I'm passing in page = 1 in the search function is because the setNextPage(1) won't have completed for that first page load.

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