Home > database >  React: How to solve the error: Object is of type 'unknown'?
React: How to solve the error: Object is of type 'unknown'?

Time:10-18

I'm trying to use the axios in order to fetch data from an API, but the response.data gives me 'unknown' error. Not sure how to fix this. Anyone can help me please. I'm using Typescript.

This is the error I'm getting:

Object is of type 'unknown'.ts(2571) (parameter) response: AxiosResponse<unknown, any>

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

export const PokemonContainer: React.FC = (props) => {
  const { pokemonItem } = props;
  const { name, height, weight, abilities } = pokemonItem;

  const [hovered, setHovered] = React.useState(false);
  const [imageLoaded, setImageLoaded] = React.useState(false);
  const [pokemon, setPokemon] = React.useState([]);


  const getPokemons = () => {
    try {
      axios
      .get('https:pokeapi.co/api/v2/pokemon')
      .then((response) => {
        setPokemon(response.data.results.map((item) => item.name));
      });
    } catch (error) {
      console.log(error);
    }
  };

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

in another file I have defined the data types:

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

CodePudding user response:

response type is unknown to TS. unknown is just a like any in the way that it can be anything, but is a safer option to it. TS will not let you access response properties since it has no idea what the object might be.

You will want to try this and use it as any.

const getPokemons = () => {
    try {
      axios
      .get('https:pokeapi.co/api/v2/pokemon')
      .then((response : any) => { 
       setPokemon(response.data.results.map((item) => item.name));
      });
    } catch (error) {
      console.log(error);
    }
  };


  • Related