Home > Enterprise >  React Native - UseEffect Constantly Updates
React Native - UseEffect Constantly Updates

Time:03-08

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.

CodePudding user response:

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).

  • Related