Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I want to change the API request based on button click. The number in the API changes and different data loads but component does not rerender

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%2C24h%2C7d`
      );
      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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading