Home > Enterprise >  useEffect is causing infinite loop when use state as dependency
useEffect is causing infinite loop when use state as dependency

Time:10-27

Here simply I am fetching data from mysql DB and storing it in state and in order to fetch this data:

const [orders, setOrders] = useState([]);

To fetch data I am using different functions and finally I am calling those functions using useEffect simple enough and so for everything is working perfectly but the problem comes whenever I use the state as dependency where I am storing data beacause if I dont do that then I have to manually refresh the page for latest changes and I have tried every given solution on stackoverflow but any of the solution didnt work so someone can please help me how can I use this state as dependencey without causing infinite loop:

const [orders, setOrders] = useState([]);
 
  const loadData = async () => {
    const response = await fetch("http://localhost/k-shop/load.php");
    const result = await response.json();
    setOrders(result);
  };
  const loadTotal = async () => {
    const response = await fetch("http://localhost/k-shop/amount.php");
    const result = await response.json();
    setTotal(result);
  };
  useEffect(() => {
    loadData();
    loadTotal();
  }, [orders]);
  console.log(orders);

CodePudding user response:

If you move the state into the useEffect dependency, you can then check if it is empty, and only set it when that check passes.

It will set the state once to populate and not pass the check again.

const [orders, setOrders] = useState([]);
 
const loadData = async () => {
  const response = await fetch("http://localhost/k-shop/load.php");
  const result = await response.json();
  setOrders(result);
};

const loadTotal = async () => {
  const response = await fetch("http://localhost/k-shop/amount.php");
  const result = await response.json();
  setTotal(result);
};

useEffect(() => {
    if(orders.length === 0) {
        loadData();
    }
    // you can do the same with checking loadTotal() state
}, [orders]);

console.log(orders);

CodePudding user response:

Avoid ,non-primitive data types in dependencyArray ,

 useEffect(() => {
    loadTotal();
    loadData();
  }, [total, orders.length]);

CodePudding user response:

every times you "setOrders" means you change the state,every times you change the state,means the "useEffect" will do again.that cause infinite loops.why not try useEffect(() => {loadData()}, [])?

  • Related