Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use if/else inside useEffect() while dispatching an action in react.js

My redux related imports are as follows -

source: https://github.com/theairbend3r/pokedex

import { useDispatch, useSelector } from "react-redux"

import {
  fetchPokemonNameUrl,
  NUMBER_OF_POKEMON,
  selectorPokemon,
} from "./pokemonCardsSlice"


const dispatch = useDispatch()
const pokemonList = useSelector(selectorPokemon)

I have a useEffect block as follows -

  useEffect(() => {
    return dispatch(fetchPokemonNameUrl())
  }, [dispatch])

What I want to do -

 useEffect(() => {
    if (pokemonList.length !== NUMBER_OF_POKEMON) {
      return dispatch(fetchPokemonNameUrl())
    }
  }, [dispatch])

But when I do this, I get a warning -

React Hook useEffect has a missing dependency: 'pokemonList.length'. Either include it or remove the dependency array.eslint(react-hooks/exhaustive-deps)

What am I doing wrong?

like image 845
theairbend3r Avatar asked May 04 '26 21:05

theairbend3r


1 Answers

Add pokemonList to the dependency array as suggested, your callback depends on the value of pokemonList (.length) which may change.

When pokemonList will be updated, the callback will run again with the updated length.

Also, you don't need to return from useEffect as it is for cleaning up an effect.

useEffect(() => {
  if (pokemonList.length !== NUMBER_OF_POKEMON) {
    dispatch(fetchPokemonNameUrl());
  }
}, [dispatch,pokemonList]);

Edit: Seems like fetchPokemonNameUrl implemented as middleware, you can rewrite as something like:

const fetchPokemonNameUrl = async (dispatch) => {
  const response = await axios.get(URL);
  const data = response.data.results;

  data.map(async (poke) => {
    const responseDetails = await axios.get(poke.url);

    let tempDetails = {
      name: responseDetails.data.species.name,
      baseExperience: responseDetails.data.base_experience,
      height: responseDetails.data.height,
      weight: responseDetails.data.weight,
      type: responseDetails.data.types[0].type.name,
      sprites: responseDetails.data.sprites.front_default,
    };

    dispatch(getData(tempDetails));
  });
};

// And call it:
useEffect(() => {
  if (pokemonList.length !== NUMBER_OF_POKEMON) {
    fetchPokemonNameUrl(dispatch);
  }
}, [dispatch,pokemonList]);
like image 103
Dennis Vash Avatar answered May 06 '26 10:05

Dennis Vash



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!