U
U
uzi_no_uzi2020-02-21 18:45:42
JavaScript
uzi_no_uzi, 2020-02-21 18:45:42

Invalid hook call, how to use the hook correctly in this case?

There is such a component

import PokemonItem from './../PokemonItem';

function PokemonList() {

    const [pokemons, setPokemons] = useState({
        pokemonList: [],
        loading: true,
    }); 

    useEffect(()=>{
        fetch('https://pokeapi.co/api/v2/pokemon/')
        .then(res => res.json())
        .then(body => {
            setPokemons({
                pokemonList: body.results,
                loading: false,
            })

        })
    }, [])




    let pokemonItems = pokemons.pokemonList.map((pokemon, index) => {
        return <PokemonItem name={pokemon.name} key={index} url={pokemon.url} />
    })


    return(
        <div className="pokemon-list">
            {pokemonItems}
        </div>
    )
}


I receive data from the server, then I create components, where I pass a link to props to get complete information on each element of the list.

In the component, I create a stateful hook for each list item:

function PokemonItem(props) {



    const [pokemon, setPokemon] = useState({
        pokemonInfo: [],
        loading: true,
    }); 




    return(
        <li className="pokemon-item">
            <div className="pokemon-item__profile">
                <img src="" alt="" className="pokemon-item__sprite"/>
                <span className="pokemon-item__name">
                    {props.name}
                </span>
            </div>
        </li>
    )
}


But I am getting this error:

Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons: 1. You might have mismatching versions of React and the renderer (such as React DOM) 2. You might be breaking the Rules of Hooks 3. You might have more than one copy of React in the same app See https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.


It seems that there are no several copies, I didn’t violate the rules of the hooks either, and the versions are normal, since it started to crash in this component, before that the hooks worked. What could be the problem?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
hzzzzl, 2020-02-21
@hzzzzl

and if in PokemonItem we rename the variable in the hook?
maybe react somehow cunningly puts everything into one function in PokemonList, and then it turns out that

pokemons.pokemonList.map((pokemon, index) => {
  .....
  const [pokemon, setPokemon] = useState({..
  // одинаковое имя переменной pokemon
})

huh, probably not

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question