1

I am learning TypeScript and I am stuck on the correct assignment for my setState that I pass to a component.

/index.tsx

import { Dispatch, SetStateAction, useState } from "react";
import FetchPokeAPI from "./api/FetchPokeAPI";
import Header from "./components/Header";
import ItemList from "./components/ItemList";

export interface IAllItems {
  name: string;
  url: string;
} [];

export default function Home() {

  const [allItems, setAllItems] = useState<IAllItems[]>([]);

  FetchPokeAPI(setAllItems);

  return (
    <>
      <Header />
      <ItemList items={allItems} />
    </>
  )
}
/FetchPokeAPI.tsx

import { Dispatch, SetStateAction, useEffect } from "react";
import { IAllItems } from "./../index";

interface IProps {
    setAllItems: Dispatch<SetStateAction<IAllItems[]>>;
    allItems: IAllItems[];
}

export default function FetchPokeAPI({setAllItems}:IProps) {
  const pokeapiURL:string = "https://pokeapi.co/api/v2/item/";

  useEffect(() => {
    fetch(pokeapiURL)
      .then((response) => response.json())
      .then((data) => {
        setAllItems(data.results);
      })
      .catch((error) => console.error(error));
  }, [pokeapiURL]);
}

I get this message:

Argument of type 'Dispatch<SetStateAction<IAllItems[]>>'
  is not assignable to parameter of type 'IProps'

Thanks in advance :)

Other forum posts have helped me a bit, but now I can't get any further.

1 Answer 1

0

because interface IProps contains 2 elements: setAllItems: Dispatch<SetStateAction<IAllItems[]>> & allItems: IAllItems[]; and you are assigning it to only setAllItems, as you didn't put your second element, allItems, in the props, you only put it in the type interface

export default function FetchPokeAPI({setAllItems}:IProps) {...

so typescript sees 2 different types, type IProps which is

{
    setAllItems: Dispatch<SetStateAction<IAllItems[]>>;
    allItems: IAllItems[];
}

and type of the current props which is

{
    setAllItems: Dispatch<SetStateAction<IAllItems[]>>;
}

so, you need to put allItems in your props

export default function FetchPokeAPI({setAllItems, allItems}:IProps) {...

and you get a correct type assignment

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.