Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

88
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda