Home > database >  React: How to solve Source has 1 element(s) but target allows only 0?
React: How to solve Source has 1 element(s) but target allows only 0?

Time:10-18

I'm trying to fetch data from an API and display them, but when I try to do the spread operator on the data array, I get error. Could someone please help with this?

This is the error I'm getting:

Argument of type '(currentArrayList: []) => [any]' is not assignable to parameter of type 'SetStateAction<[]>'. Type '(currentArrayList: []) => [any]' is not assignable to type '(prevState: []) => []'. Type '[any]' is not assignable to type '[]'. Source has 1 element(s) but target allows only 0. TS2345

This is the code:

const API_URL = 'https:pokeapi.co/api/v2/pokemon';

interface Props {
  pokemonItem: PokemonItem[];
  children: React.ReactNode | React.ReactNode[];
} 


export const PokemonContainer: React.FC = (props) => {
  const [pokemon, setPokemon] = React.useState([]);
  const [loadItems, setLoadItems] = React.useState(API_URL);

  const getPokemons = async () => {
    const response: any = await fetch(loadItems);
    const data = await response.json();

    setLoadItems(data.next);
    setPokemon(response.data.results[0].name);

    console.log(response.data.results);

    const getEachPokemon = (result: any) => {
      result.forEach(async (element: any) => {
        const response = await fetch(
          `https:pokeapi.co/api/v2/pokemon/${element.name}`
        );
        const data = await response.json();
        setPokemon((currentArrayList) => [...currentArrayList, data]);
      });
    };

    getEachPokemon(data.results);
    await console.log(pokemon);
  };

  React.useEffect(() => {
    getPokemons();
  }, []);

Update:

export interface PokemonItem {
    id: number;
    name: string;
    height: string;
    weight: string;
    abilities: string;
}

CodePudding user response:

Its because const [pokemon, setPokemon] = React.useState([]); is not typed. If you add a type to the useState itll stop complaining, e.g: React.useState<any[]>([]).

However, I would recommend not using any and actually creating a type that reflects what a pokemon would look like. I would also recommend not using any in the other places of your code and try to use types as much as possible :)

  • Related