-2

I am trying to fetch some data from a free api https://catfact.ninja/fact using axios in nextjs but getting promise pending.

httpClient.js:

import axios from "axios";

const GET_CATS = "https://catfact.ninja/fact";

export const getCats = async () => {
  try {
    return await axios.get(GET_CATS);
  } catch (e) {
    console.log("ERROR", e.message);
  }
};

index.js:

import { getCats } from "./api/httpClient";

const Home = ({ data }) => {
  console.log(getCats());
  return <div></div>;
};

export default Home;

So i am confused why the promise is not resolving as i am already async await the api call in httpClient.js

enter image description here

John
  • 1,595
  • 4
  • 21
  • 44
  • 1
    As you can see on your very last screenshot - - this is how the browser's console logged your promise initially, at the moment when you called the function and got a promise from it. But browser's console can reflect changes if you expand the object.. so you can see PromiseState: "fulfilled".. And `async` functions return type is `promise`, and you need to either `await` the `async` function (result), either to use `.then(x => doSomething)` on it. So not really clear why you are confused. Moreover, you even see the `PromiseResult`. Try to expand it :) – Sergey Sosunov Oct 05 '22 at 00:01
  • 1
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call). _TL;DR_ `getCats().then(console.log)` – Phil Oct 05 '22 at 00:17
  • 1
    Your `catch` turns a failed promise into a successful one that resolves with `undefined`. Don't do that as it's confusing to anything using your function. I would simply use `export const getCats = async () => (await axios.get(GET_CATS)).data;` – Phil Oct 05 '22 at 00:21
  • Finally, stop using the console to verify your application's state. Use the data in your application instead – Phil Oct 05 '22 at 00:24
  • Does this answer your question? [Why is my asynchronous function returning Promise { } instead of a value?](https://stackoverflow.com/questions/38884522/why-is-my-asynchronous-function-returning-promise-pending-instead-of-a-val) I simply searched "StackOverflow promise pending" and this came up. I strongly encourage you to search for existing answers to the concept prior to posting a question. – rantao Oct 05 '22 at 01:02

1 Answers1

2

As the commenter said - you're not waiting for the result in your component. getCats returns a promise, so you need to do something with the result when it gets fulfilled:

import { useState } from "react";
import { getCats } from "./api/httpClient";

const Home = () => {
  const [data, setData] = useState(null);
  
  useEffect(() => {
    getCats().then(result => setData(result.data));
  }, []);

  return <div>{data?.fact}</div>;
};

export default Home;
gerrod
  • 6,119
  • 6
  • 33
  • 45