0

I want to fetch some data on my React page and it gets the result correctly.

However, regardless of the fetch result, its Promise status is still Pending.

Promise still in Pending

And here's my code:

const config = require("./config.json");

function App() {
  const getSongs = (keyword) => {
    return fetch(
      `https://api.genius.com/search?q=${keyword}&access_token=${config.genius.token}`
    )
      .then((res) => res.json())
      .then((json) => json.response.hits)
      .catch((err) => err);
  };
  console.log(getSongs("faded"));
  return <div className="App"></div>;
}

export default App;

I already tried async/await, but it didn't work.

Is there any solution for this situation?

Gary Lee
  • 3
  • 2
  • 1
    For side effects & async operations in React you need to use an [`useEffect` hook](https://reactjs.org/docs/hooks-effect.html). You may also need a [state hook](https://reactjs.org/docs/hooks-state.html). Just go through the docs – Vaibhav Vishal Feb 11 '21 at 12:25
  • `I already tried async/await, but it didn't work` How? Because it is clearly the solution. It says the Promise is still pending because you are `console.log`ging it immediately, long before it resolves. It will resolve later, inside the `.then()` – Jeremy Thille Feb 11 '21 at 12:26

0 Answers0