By using this site, you agree to the Privacy Policy and Terms of Use.
Accept
rocoderesrocoderes
  • Home
  • HTML & CSS
    • Login and Registration Form
    • Card Design
    • Loader
  • JavaScript
  • Python
  • Internet
  • Landing Pages
  • Tools
    • Google Drive Direct Download Link Generator
    • Word Count
  • Games
    • House Painter
Notification Show More
Latest News
How to set the dropdown value by clicking on a table row
Javascript – How to set the dropdown value by clicking on a table row
JavaScript
Attempting to increase the counter, when the object's tag exist
Javascript – Attempting to increase the counter, when the object’s tag exist
JavaScript
Cycle2 JS center active slide
Javascript – Cycle2 JS center active slide
JavaScript
Can import all THREE.js post processing modules as ES6 modules except OutputPass
Javascript – Can import all THREE.js post processing modules as ES6 modules except OutputPass
JavaScript
How to return closest match for an array in Google Sheets Appscript
Javascript – How to return closest match for an array in Google Sheets Appscript
JavaScript
Aa
Aa
rocoderesrocoderes
Search
  • Home
  • HTML & CSS
    • Login and Registration Form
    • Card Design
    • Loader
  • JavaScript
  • Python
  • Internet
  • Landing Pages
  • Tools
    • Google Drive Direct Download Link Generator
    • Word Count
  • Games
    • House Painter
Follow US
High Quality Design Resources for Free.
rocoderes > JavaScript > Javascript – How to prevent continuous axios API requests in useEffect()?
JavaScript

Javascript – How to prevent continuous axios API requests in useEffect()?

Admin
Last updated: 2023/12/20 at 4:38 PM
Admin
Share
2 Min Read
How to prevent continuous axios API requests in useEffect()?

Problem:

I am working on a React JS app, where I need to fetch transactions from the backend and display it to the user. Here, I am fetching and displaying transactions with Pagination (50 transactions at once). I have used an useEffect() hook with pageNo in the dependency array so that whenever the page changes new transactions get fetched. Here is my code:

Contents
Problem:Solution:You just need to add a cleanup function at the end of useEffect.refs
  useEffect(() => {
    setLoading(true);
    axios
      .get(`${TRANSACTIONS_ENDPOINT}`, {
        params: {
          page: paginationConfig.pageNo,
          search_by: searchConfig.search_by,
          search_value: searchConfig.search_value
        },
      })
      .then((response) => {
        const { transactions, total_pages, page} = response.data;
   
        setTransactions(transactions);
        setPaginationConfig({
          ...paginationConfig,
          pageNo: page,
          totalPages: total_pages,
        });
        setLoading(false);
        sessionStorage.setItem(PAGE_STORAGE_KEY, page.toString());
      })
      .catch((err) => {
        console.error(err);
      });
  }, [paginationConfig.pageNo]);

It is working as expected whenever the user navigates to a different page using page navigation at the bottom of the table. However, in the case when a user rapidly changes the page, it keeps on refreshing with pages fluctuating between different page numbers and keeps on making continuous API requests.

Solution:

You just need to add a cleanup function at the end of useEffect.

setup: The function with your Effect’s logic. Your setup function may also optionally return a cleanup function. When your component is added to the DOM, React will run your setup function. After every re-render with changed dependencies, React will first run the cleanup function (if you provided it) with the old values, and then run your setup function with the new values. After your component is removed from the DOM, React will run your cleanup function.

  useEffect(() => {
    let flag = true;
    if(flag) {
      // do your Axios logic here
    }
    // cleanup ✅
    return () => {
      flag = false;
    };
  }, [paginationConfig.pageNo]);

refs

https://react.dev/reference/react/useEffect

Related

Subscribe to Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Share this Article
Facebook Twitter Email Print
What do you think?
Love0
Sad0
Happy0
Sleepy0
Angry0
Dead0
Wink0
Previous Article Having a hard time using chrome.tabs.sendMessage Javascript – Having a hard time using chrome.tabs.sendMessage
Next Article Why does this dark mode code made with Jquery works? Javascript – Why does this dark mode code made with Jquery works?
Leave a comment Leave a comment

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

- Advertisement -

You Might Also Like

How to set the dropdown value by clicking on a table row

Javascript – How to set the dropdown value by clicking on a table row

February 11, 2024
Attempting to increase the counter, when the object's tag exist

Javascript – Attempting to increase the counter, when the object’s tag exist

February 11, 2024
Cycle2 JS center active slide

Javascript – Cycle2 JS center active slide

February 10, 2024
Can import all THREE.js post processing modules as ES6 modules except OutputPass

Javascript – Can import all THREE.js post processing modules as ES6 modules except OutputPass

February 10, 2024
rocoderesrocoderes
Follow US

Copyright © 2022 All Right Reserved By Rocoderes

  • Home
  • About us
  • Contact us
  • Disclaimer
Join Us!

Subscribe to our newsletter and never miss our latest news, podcasts etc.

Zero spam, Unsubscribe at any time.
Welcome Back!

Sign in to your account

Lost your password?