Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

85
Views
React Native - UseEffect Constantly Updates

I am using useEffect to get the total jigsaw pieces from my async storage to be displayed on the home page. I use async storage to get the number of jigsaws stored in the storage then for each jigsaw, i add the total amount of jigsaw pieces. I do this within useEffect as the total amount of jigsaw pieces may change depending on if the user adds more jigsaw to their collection. However, when i use useEffect, my total amount of jigsaw pieces constantly updates and never stops.

Code:

let [totalPieces, setTotalPieces] = useState(0);
  const [numJigsaw, setNumJigsaw] = useState([]);
  const getNumOfJigsaw = async () => {
    try {
      setNumJigsaw(await AsyncStorage.getAllKeys());
    } catch (e) {}
    return numJigsaw;
  };
  const getAllJigsaw = async () => {
    let jigsaws = await getNumOfJigsaw();
    for (let z = 0; z < jigsaws.length; z++) {
      let currentJigsaw = JSON.parse(await AsyncStorage.getItem(jigsaws[z]));
      setTotalPieces(totalPieces+ parseFloat(currentJigsaw.pieces));
    }
  };
  useEffect(() => {
    getAllJigsaw();
  }, [totalPieces]);

I believe the issue is because totalPieces is dependant? Im not entirely sure though.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Yes - you've set the effect to run when totalPieces changes (via the dependency).

The effect (when the async stuff resolves) sets totalPieces, so the effect is run again due to that dependency, etc, etc.

It sounds like you're looking for something like

const [totalPieces, setTotalPieces] = useState(0);
const [jigsawKeys, setJigsawKeys] = useState([]);
useEffect(() => {
  (async () => {
    const jigsaws = await AsyncStorage.getAllKeys();
    let total = 0;
    for (let z = 0; z < jigsaws.length; z++) {
      let currentJigsaw = JSON.parse(await AsyncStorage.getItem(jigsaws[z]));
      total += parseFloat(currentJigsaw.pieces);
    }
    setJigsawKeys(jigsaws);
    setTotalPieces(total);
  })();
}, [totalPieces]);

all in all (I renamed numJigsaw to jigsawKeys so it makes more sense).

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!