Home > Back-end >  React Native UseEffect stuck in loop calling function
React Native UseEffect stuck in loop calling function

Time:10-13

I am trying to update a state based on a user's touch event, and then I use useEffect to try to call a function where it updates another state so that it can be passed to the next screen by using navigation.

The problem is I am getting stuck in a loop and I have no idea why. It should only be called when the selectedSet is updated.

  const [pokemonCards, setPokemonCards] = useState([]);
  const [selectedSet, setSelectedSet] = useState("");

  useEffect(() => {
    const getPokemonCards = () => {
      PokemonTCG.findCardsByQueries({ q: 'set.id:'   selectedSet, pageSize: 10 }).then(
        (cards) => {
          console.log("cards: ", cards)
          setPokemonCards(cards);
        }
      )
    }
    getPokemonCards();
  }, [selectedSet]);

...

  <TouchableHighlight key={pokemonSet.id} onPress = {() => {
    setSelectedSet(pokemonSet.id);
    navigation.navigate("SetDetails", { setID: pokemonSet.id, pokemonSetDetails: pokemonSet, pokemonCards: pokemonCards });
  }}>

CodePudding user response:

I guess its pokemonSet.id that make the useEffect function reload again and create this side effect. Could you show the full code of your component to make things clearer ?

CodePudding user response:

The 'useEffect' refetches the pokemon cards, which creates new pokemontSet objects, which rerenders the object with the "new" selected pokemonSet.id. And because the selectedId is changed the effect is triggered.

  • Related