2021年4月8日星期四

Getting TypeError after Async API Call with axios

I'm trying to figure out some things that are occurring on my code. I'm fetching some data from an Rest API I've made, and after an async call I'm getting:

TypeError: Cannot read property 'field' of undefined

I can't figure out what is happening, because when I log the data on the console, I can see my Object populated with the correct info. Just to be sure that I've not made a type mistake, I've copied the data from the console.log(response) and created an Object and it worked.

Here's the call:

import axios from 'axios';    const url_service_villain = "https://some_url/"    export const findRandomVillain = async () => {      try {          const {data} = await axios.get(url_service_villain + "find/random");          return await data      } catch (err) {          console.log(err);      };  };  

And here is where I call the method:

import React from 'react';    import Character from './components/Character'    import {findRandomVillain} from './services/VillainService';    async function getRandomVillain(){    const data = await findRandomVillain();    console.log(data);    return data;  }    function CharacterList(){     const char = getRandomVillain();    return (      <section className="characterList">        <Character key={char.id} images={char.images.md} name={char.name} powerstats={char.powerstats}/>      </section>        )  };    export default CharacterList;  

On the method getRandomVillain() the console.log(data) prints the object that I want, but on the CharacterList I get the TypeError I listed above.

I also noticed on the top on the console window the following:

Promise {<pending>}  App.js:17  Promise {<pending>}  App.js:17  App.js:20 Uncaught TypeError: Cannot read property 'md' of undefined      at CharacterList (App.js:20)  ...{/*long list of errors here*/}  {id: "123", name: "Sinestro", powerstats: {…}, images: {…}} App.js:11  {id: "123", name: "Sinestro", powerstats: {…}, images: {…}} App.js:11  {id: "123", name: "Sinestro", powerstats: {…}, images: {…}} App.js:11  

I think that is something related to the async call, and I don't know why the last line repeat 3 times, since I'm only logging it once.

https://stackoverflow.com/questions/67014401/getting-typeerror-after-async-api-call-with-axios April 09, 2021 at 10:46AM

没有评论:

发表评论