Home > Back-end >  fetch request with different parameters on every click
fetch request with different parameters on every click

Time:10-30

Im using an API and I fetch 9 pictures every time from said API. the API can display "pages", meaning if a "page=1" parameter is passed in the request I get the first 9 pictures from the database. "page=2" gives me the next 9 pictures and so on.

I want to have 2 buttons so on every click I get the next 9 pictures. I tried to do so using the API parameter change but haven't had much luck.

I ran across this thread:

Setting query string using Fetch GET request

but either it doesnt help me or I dont understand it enough. Thanks!

my code is below:

const Home = ()=>{

let pageNumber = 1;

const [photosData, SetPhotosData] = useState([])
const url = `https://pixabay.com/api/?key=25540812-faf2b76d586c1787d2dd02736&per_page=9&page=`

const getImages = async()=>{
    try {
        const response = await fetch (url pageNumber)
        if (!response.ok) {
            throw new Error();
        }
        const responseObj = await response.json();
        const allPhotosData = responseObj.hits

        SetPhotosData(allPhotosData)
    } 
    catch (error) {
        console.log(error);
    }
}


 useEffect(()=>{
    getImages();
  },[])

const getNextPage = ()=> {
    pageNumber  ;
    console.log(pageNumber);
    getImages();
}


const getPrevPage =()=>{
    pageNumber--;
    console.log(pageNumber);
    getImages();
}
return(
<div>
    <button onClick={getPrevPage}>prev</button>
    <button onClick={getNextPage}>next</button>

    <br/>

    {photosData.map(singlePhotoData=>
        <img 
        key={singlePhotoData.id}
        src={singlePhotoData.largeImageURL}
         />)}
</div>
)

}

export default Home;

CodePudding user response:

Your pageNumber will reset to 1 everytime you set a new state with SetPhotosData. You could fix this by using useRef.

const pageNumber = useRef(1);

...

const response = await fetch(url   pageNumber.current);

...

const getNextPage = () => {
  pageNumber.current  ;
  console.log(pageNumber.current);
  getImages();
};

const getPrevPage = () => {
  if (pageNumber.current < 2) return;
  pageNumber.current--;
  console.log(pageNumber.current);
  getImages();
};

Note that we also check if the pageNumber is not lower than 2 before decreasing it and calling the api to prevent the api from throwing a error, saying it has no page 0

  • Related