Home > front end >  I want to change the API request based on button click. The number in the API changes and different
I want to change the API request based on button click. The number in the API changes and different

Time:01-17

I have a crypto coin API which gives results based on page number. So I want to change the number in the call based on pagination buttons. The number changes but the data does not reload.

const [activePage, setActivePage] = useState(8);
  const getCoinsData = async () => {
    try {
      const response = await Axios.get(
        `https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&per_page=100&page=${activePage}&sparkline=true&price_change_percentage=1h,24h,7d`
      );
      setData(response.data);
      setLoading(false);
    } catch (e) {
      console.log(e);
    }
  };



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

This is the pagination structure

<div className="home-pagination">
        <div
          className={
            activePage === 1 ? "pagination-button active" : "pagination-button"
          }
          onClick={() => setActivePage(1)}
        >
          1
        </div>
        <div
          className={
            activePage === 2 ? "pagination-button active" : "pagination-button"
          }
          onClick={() => {
            setActivePage(2);
          }}
        >
          2
        </div>
</div>

How do I re-render the component so the new data loads based on new page number.v

CodePudding user response:

Your state is updating properly n every page click. The only thing you need to do is call the API again. You can handle it in useEffect

  useEffect(() => {
    getCoinsData();
  }, [activePage]);

by adding activePage as a dependency to useEffect, it will call getCoinsData API on every activePage change

  •  Tags:  
  • Related